雙鏈表與單鏈表的比較


  雙鏈表在一定程度上就是單鏈表的的基礎上加上了一個指針域,在一些情況下能夠使程序更加健壯和速率更加高效。

  雙鏈表的結點定義

  typedef struct node

{

  int data;

  struct node *next;

  struct node *prior;

}node;

雙鏈表的定義

  typedef struct doublelist

{

  node *head;

  node *tail;

  size_t size;

}doublelist;

鏈表的初始化

doublelist *list;

list = (doublelist *)malloc(sizeof(doublelist));

list->head = NULL;

list->tail = NULL;

list->size = 0;

頭插:

1.在每次插入新結點是進行一次該雙鏈表是否為空的判斷,若為空則頭結點為創建的新結點。

 list->head = newnode;

 list->tail = newnode;

2.若鏈表不為空:

 newnode->next = list->head;//當鏈表為空時插入頭結點時,頭結點等於尾結點

 list->head->prior = newnode;

 list->head = newnode;

尾插:

在插入之前進行一次判斷

1.鏈表為空鏈表時:

 list->tail = newnode;

 list->head = newnode;

2.鏈表不為空時:

 newnode->prior = list->tail;

 list->tail->next = newnode;

 list->tail = newnode;

雙鏈表的遍歷

1.正向遍歷

node *tmp;

tmp = list->head;

while(tmp){

  printf("%d\n",tmp->data);

  tmp = tmp->next;

}

2.反向遍歷

node *tmp;

tmp = list->tail;

while(tmp){

printf("%d\n",tmp->data);

tmp = tmp->next;

}

具體的代碼實現:github中zou-ting-rong/sample


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM