数据结构--双链表的创建和操作
2015-06-26 14:12
501 查看
一、双向链表的定义
双向链表也叫双链表,是链表的一种,它的每个数据结点中都有两个指针,分别指向直接后继和直接前驱。所以,从双向链表中的任意一个结点开始,都可以很方便地访问它的前驱结点和后继结点。一般我们都构造双向循环链表。注意:在实现的过程中,要分清前驱指针和后继指针,不要把他们当成一个指针。
//双向链表的实现 template<typename T>struct node{ T data; node<T> *prior,*next; };
二、双向链表的实现
template<typename T>class nLink { private: node<T> *head; public: nLink() { head=new node<T>; head->next=head->prior=NULL; } ~nLink() { } //清空双链表 void clearLink() { node<T> *p=head->next,*q=NULL; while(p) { q=p->next; delete p; p=q; } head->next=NULL; } //销毁双链表 void destoryLink() { clearLink(); if (head) { delete head; head=NULL; } } //打印双链表 void printLink() { node<T> *p=head->next; while(p) { cout<<p->data<<" "; p=p->next; } cout<<endl; } //在双链表末尾添加结点 bool appendLink(T e) { node<T> *p=head,*s=NULL; s=new node<T>; if (s==NULL) return false; s->data=e; s->next=s->prior=NULL; while(p->next) { p=p->next; } p->next=s; s->prior=p; return true; } //获取链表的长度 int length() { node<T> *p=head; int lenth=0; if (p==NULL) return 0; while(p) { p=p->next; lenth++; } return lenth; } //在第pos个位置插入新节点 bool insertLink(int pos,T e) { node<T> *p=head; int posflag=0; while(p&&posflag<pos-1) { p=p->next; ++posflag; } node<T> *s=new node<T>; if (s==NULL) return false; s->data=e; s->next=s->prior=NULL; if (p==NULL||posflag>pos-1) { return false; } s->next=p->next; if(p->next!=NULL) p->next->prior=s; p->next=s; s->prior=p; return true; } //删除第i个位置上的节点 bool deleteLink(int pos) { node<T> *p=head; if (pos>length()||pos<1) { return false; } int posflag=0; while(p && posflag<pos-1) { p=p->next; ++posflag; } if (p && p->next==NULL) { p->prior->next=NULL; delete p; p=NULL; } else{ p->prior->next=p->next; p->next->prior=p->prior; delete p; p=NULL; } return true; } //删除制定元素的节点 bool deleteLink(T e) { node<T> *p=head; while (p) { if (p->data==e) { break; } p=p->next; } if(p==NULL) { cout<<"can not find the elem:"<<e<<endl; return false; } //判断要删除的是不是尾节点 if (p->next==NULL) { p->prior->next=NULL; delete p; p=NULL; } else{ p->prior->next=p->next; p->prior=p->next->prior; delete p; p=NULL; } return true; } };
测试工作
int main() { nLink<char> link; for (int i=0;i<10;i++) { link.appendLink('a'+i); } link.insertLink(11,'s'); cout<<"Length:"<<link.length()<<endl; link.printLink(); link.deleteLink('s'); link.printLink(); cout<<"Length:"<<link.length()<<endl; system("pause"); return 0; }
参考地址:http://www.oschina.net/code/snippet_250934_12063
相关文章推荐
- COJ986 WZJ的数据结构(负十四)
- POJ 1741 Tree (树上点分治)(楼教主男人八题之一)
- 数据结构之---C语言实现线索二叉树
- 数据结构-图之强连通
- 数据结构概述
- 数据结构习题之绪论
- php面试题之二——数据结构和算法(高级部分)
- 白话算法与数据结构之【字典树】
- 数据结构和算法系列 - 跳跃表 SkipList
- IplImage 数据结构
- 循环Map的错误做法
- 数据结构《21》----2014 WAP 第一个问题----Immutable queue
- c#数据结构之顺序表
- [数据结构]c++注释转化为c语言注释
- xHCI驱动学习(1) 核心数据结构
- Python——基本数据结构
- 按层次遍历二元树
- Joomla添加分类和文章时的目录数据结构
- 数据结构和算法经典100题-第18题
- Redis 链表的数据结构