【发布时间】:2014-02-26 00:12:55
【问题描述】:
我正在尝试为循环双向链表的字符串值编写插入函数。我看到创建一个虚拟节点有利于这样做,因此我可以消除特殊情况,例如列表为空时。问题是我没有找到很多关于虚拟头节点的好信息。我理解他们的目的,但我不明白我是如何创建/实现它的。
感谢所有代码示例,尽管有人可以查看它,但我自己试图弄清楚它有点卡住了。
#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 知道自己的头部。您的插入函数应该接受一个要插入的值,找到插入新节点的位置并插入该节点。看起来它是按降序插入的。
-
而且您只需要 1 个节点(head 或 dummyHead),无论您喜欢哪个。该节点也称为哨兵节点。
标签: c++ linked-list