数据结构 《3》----双向链表(带有头节点)
2014-01-15 21:48
417 查看
本文参照了 C与指针中双向链表的实现,力求简单明了。
双向链表带有一个头节点,
头节点的pre指针指向链表的最后一个node;
next指向第一个node;
val 表示链表的长度。
![](http://img.blog.csdn.net/20140115222024937?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvc2hvdWxpbmp1bg==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast)
双向链表带有一个头节点,
头节点的pre指针指向链表的最后一个node;
next指向第一个node;
val 表示链表的长度。
// copyright @ L.J.SHOU Jan.15, 2014 // double-linked-list with a head node #include "double-linked-list.h" #include <iostream> using namespace std; struct ListNode{ ListNode *pre; ListNode *next; int val; ListNode(int x=0) : val(x), pre(NULL), next(NULL){} }; // return pointer to a head node // list->val------length of list // list->pre------the last node of list // list->next---- the first node of list ListNode* NewList() { return new ListNode(0); } ListNode* Destroy(ListNode *list) { ListNode *next(NULL); while(list){ next = list->next; delete list; list = next; } return NULL; } // actually, no need to return head node's pointer // since heading node never change ListNode* Insert(ListNode *list, int x) { ListNode *pre(list), *cur(list->next); ListNode *node(NULL); while(cur && cur->val < x) { pre = cur; cur = cur->next; } if(cur && cur->val == x) return list; node = new ListNode(x); node->next = cur; pre->next = node; // insert at first if(pre != list) node->pre = pre; else node->pre = NULL; //insert at rear if(cur != NULL) cur->pre = node; else list->pre = node; list->val ++; // length++ return list; } ListNode* Delete(ListNode *list, int x) { ListNode *pre(list), *cur(list->next); while(cur && cur->val != x) { pre = cur; cur = cur->next; } if(cur && cur->val == x) { pre->next = cur->next; //最后一个节点删除单独处理(相当与首节点删除) if(cur->next != NULL) cur->next->pre = cur->pre; //cur->pre 而不是 pre else list->pre = cur->pre; delete cur; --list->val; } return list; } void PrintList(ListNode *list) { cout << "Length of list: " << list->val << endl; list = list->next; while(list){ cout << list->val << " "; list = list->next; } cout << endl; } void ReversePrintList(ListNode *list) { list = list->pre; while(list){ cout << list->val << " "; list = list->pre; } cout << endl; } int main(void) { ListNode *list = NewList(); for(int i=10; i>0; --i) list = Insert(list, i); list = Delete(list, 1); list = Delete(list, 5); list = Delete(list, 10); PrintList(list); ReversePrintList(list); list = Destroy(list); return 0; }
相关文章推荐
- 数据结构 《3》----双向链表(带有头节点)
- 数据结构示例之带头节点的双向循环链表
- 数据结构示例之带头节点的双向循环链表
- 数据结构之双向带头节点带环链表的实现
- 数据结构练习--双向链表的实现
- C++数据结构---链表(链表节点创建)
- 数据结构 反转单向链表和双向链表
- 数据结构-有头双向循环链表
- 复习下C 链表操作(双向循环链表,查找循环节点)
- 带头节点的双向循环链表(数据结构)(带有遍历)
- 双向链表添加节点和删除结点
- 数据结构 - C语言版 - 双向链表 所有基本操作
- Linux c 算法与数据结构--双向链表
- 每天一道LeetCode-----复制一个带有随机节点的链表
- 温习之数据结构----双向链表
- 数据结构学习笔记三 循环链表及双向链表
- 数据结构:遍历一次获得链表的倒数第N个节点
- 数据结构 -- 单链表插入之包含头节点的插入
- 用只含一个链域的节点实现循环链表的双向遍历
- 数据结构(C#)--双向链表