資料結構中單鏈表中的 頭插法和尾插法
阿新 • • 發佈:2019-01-03
正在學習資料結構中的連結串列,在有沒有頭節點的問題上的 頭插法跟尾插法一直模糊。。。。。
作為一個新手,整理了一下在有節點時的 頭插法跟尾插法
頭插法程式碼:
int InsertHread(LinkList &L,int e) { LinkList tamp = L->next; //建立一個新的變數指向首元結點 LinkList s = new LNode; if (s == NULL) { return false; } s->date = e; s->next = tamp; L->next = s; L->Length++; return 1; }
如圖:最開始頭節點L節點指向tamp節點,先獲取tamp節點,讓新增的s節點指向tamp節點,然後再讓頭節點L指向節點。
它的型別為越前邊插入的資料的越排在後面。
尾插法程式碼:
int InsertTail(LinkList &L, int e) { LinkList tamp = L; while (tamp->next != NULL) { tamp = tamp->next; } LinkList s = new LNode; if (s == NULL) { return false; } s->date = e; s->next = NULL; tamp->next = s; L->Length++; return true; }
先遍歷連結串列直到遍歷到最後一個節點,再把最後一個節點的next指向新的節點。