双链表相对于单链表来说,多了只想前一个Node的指针。假如有N个node的话,多了N个指针,换来了比单链更灵活的遍历(可以倒着来了),是不是需要这样,it all depends.
双链表实验:one way or round trip? round trip!
#include <stdio.h> #include <stdlib.h> struct DList{ int data; DList* prev; DList* next; DList(){} DList(int d){ data = d; prev = NULL; next = NULL; } DList(int d, DList* p, DList* n){ data = d; prev = p; next = n; } }; DList* appendToTail(int d, DList* head){ DList* p = head; while(p->next!=NULL){ p = p->next; } DList* temp = new DList(d,p,NULL); p->next = temp; return head; } void print_round_trip(DList* head){ DList* p = head; DList* temp; while(p!=NULL){ if(p->next==NULL){ printf("%d\n",p->data); }else{ printf("%d -> ",p->data); } temp = p; p = p->next; } //the last node; p = temp; while(p!=NULL){ if(p->prev==NULL){ printf("%d\n",p->data); }else{ printf("%d -> ",p->data); } p = p->prev; } } int main(){ DList* head = new DList(23); head = appendToTail(21,head); head = appendToTail(2,head); head = appendToTail(877,head); print_round_trip(head); return 0; }
浙公网安备 33010602011771号