我想爲圓形雙向鏈表寫入字符串值的插入函數。我看到創建一個虛擬節點對於這樣做是有益的,因此我可以消除特殊情況,例如列表爲空時。問題是我在虛擬頭節點上找不到很多好的信息。我瞭解他們的目的,但我不明白我如何創建/實施它。虛擬頭節點鏈接列表
欣賞所有的代碼示例傢伙,試圖找出我自己得到一點卡住,雖然如果有人可以看看它。
#include <iostream>
#include <string>
using namespace std;
typedef string ListItemType;
struct node {
node * next;
node * prev;
ListItemType value;
};
node * head;
node * dummyHead = new node;
void insert(const ListItemType input, node * & within);
void main(){
insert("bob",dummyHead);
}
void insert(const ListItemType input, node * &ListHead){
node *newPtr = new node;
node *curr;
newPtr->value = input;
curr = ListHead->next; //point to first node;
while (curr != ListHead && input < curr->value){
curr = curr->next;
}
//insert the new node pointed to by the newPTr before
// the node pointed to by curr
newPtr->next = curr;
newPtr->prev = curr->prev;
curr->prev = newPtr;
newPtr->prev->next = newPtr;
}
您的插入函數不應該需要第二個參數ListHead,因爲List知道它自己的頭部。您的插入函數應該接受一個要插入的值,找到插入新節點並插入節點的位置。它看起來像是按降序插入。 – anonymous
而你只需要1個節點(head或dummyHead),以你的偏好爲準。該節點也稱爲sentinel節點。 – anonymous