listy dwukierunkowe

0

Witam, muszę napisać funkcje która doda element na koniec listy dwukierunkowej. Poniżej zamieszczam moją wersję. Moje pytanie brzmi , czy potrzebne jest deklarowanie wskaźnika w ? i czy dodajac element na koniec nie powinienem tego robić za ogona wskazującego na koniec zamiast head ?

 void addEnd(struct list *head,int x){								
	struct list *newPrev=(struct list*)malloc(sizeof(struct list));
	struct list *w=head;
	while(w->next)	
			w=w->next;
	newPrev->next=NULL;
	newPrev->key=x;
	newPrev->prev=w;
	w->next=newPrev;
}
1
#include <stdio.h>
#include <stdlib.h>

typedef struct node
  {
   int value;
   struct node *prev,*next;
  } node;
 
typedef struct
  {
   node *head,*tail;
  } list;
 
node *makenode(int value,node *prev,node *next)
  {
   node *tmp=(node*)malloc(sizeof(node));
   tmp->value=value;
   tmp->next=next;
   tmp->prev=prev;
   return tmp;
  }
 
void addtail(list *lst,int value)
  {
   node *tmp=makenode(value,lst->tail,NULL);
   if(lst->tail) lst->tail->next=tmp;
   else lst->head=tmp;   
   lst->tail=tmp;
  }
 
void addhead(list *lst,int value)
  {
   node *tmp=makenode(value,NULL,lst->head);
   if(lst->head) lst->head->prev=tmp;
   else lst->tail=tmp;
   lst->head=tmp;
  }

void remove(list *lst,node *fnd)
  {
   if(fnd)
     {
      if(fnd->prev) fnd->prev->next=fnd->next;
      else lst->head=fnd->next;
      if(fnd->next) fnd->next->prev=fnd->prev;
      else lst->tail=fnd->prev;
      free(fnd);
     }
  }

void clean(list *lst)
  {
   while(lst->head)
     {
      lst->tail=lst->head;
      lst->head=lst->head->next;
      free(lst->tail);
     }
   lst->tail=NULL;
  }
 
void showHead(list *lst)
  {
   node *i;
   printf("{ ");
   for(i=lst->head;i;i=i->next) printf("%d ",i->value);
   printf("}\n");
  }
 
void showTail(list *lst)
  {
   node *i;
   printf("{ ");
   for(i=lst->tail;i;i=i->prev) printf("%d ",i->value);
   printf("}\n");
  }

int main()
  {
   int i;
   list lst={NULL,NULL};
   showHead(&lst);
   for(i=0;i<5;++i) addtail(&lst,i);
   showHead(&lst);
   for(i=1;i<5;++i) addhead(&lst,-i);
   showHead(&lst);
   showTail(&lst);
   clean(&lst);
   return 0;
  }

1 użytkowników online, w tym zalogowanych: 0, gości: 1