下面的代码用一个”哨兵“实现双链表,感觉很简洁,中间也有点绕,暂时实现,供学习之用
static Node list_handle = { &list_handle,&list_handle, }; bool addNode(Node* node) { if (node == NULL) { return false; } Node* guard = &list_handle; node->next = guard; node->prev = guard->prev; node->prev->next = node; node->next->prev = node; } void removeNode(Node *node) { if (node == NULL) { return; } node->prev->next = node->next; node->next->prev = node->prev; node->prev = NULL; node->next = NULL; } void travel() { for (Node *node = list_handle.next;node != &list_handle ; node = node->next) { //对每个节点所进行的操作,这里只是简单的打印 cout<< node->data <<""<<endl; } }
使用方法
int _tmain(int argc, _TCHAR* argv[]) { Node n1; n1.data = 100; Node n2; n2.data = 200; Node n3; n3.data = 300; addNode(&n1); addNode(&n2); addNode(&n3); travel(); removeNode(&n2); travel(); return 0; }