数据结构——链表(linkedlist)
基本分类:
1、单向链表
2、带尾指针的单向链表
3、双向循环链表
以下分类进行说明
1、单向链表
基本元素:*front //头节点
*next //下一节点
声明:node<T>*p;
初始化:p=new node<T>(nodeValue,nextpointer);
简单遍历:
1 template <typename T> 2 void writeLinkedList(node<T> *front) 3 { 4 node<T> *curr; 5 curr=front; 6 while(curr!=NULL) 7 { 8 cout<<curr->nodeValue<<" "; 9 curr=curr->next; 10 } 11 }
插入元素
- 插在表头:
node<T> *newnode;
newnode=new node<T>(item,front); //使新节点的next指向头指针
front=newnode; //使新节点成为头指针
- 插在某位置:
node<T> *prev=NULL,*curr=front;
while(curr->nodevalue!=searchItem){
prev=curr;
curr=curr->next;
}
newnode->next=curr;
prev->next=newnode;
删除元素
- 删表头
node<T> *curr=front;
front=front->next;
delete curr;
- 删某元素
node<T> *prev=NULL,*curr=front;
while(curr->nodevalue!=searchItem){
prev=curr;
curr=curr->next;
}
prev->next=curr->next;
delete curr;
具体代码实现:
1 void eraseValue(node<T> *front,const T &target) 2 { 3 node<T>*curr=front,*prev=NULL; 4 bool FoundItem=false; 5 while(curr!=NULL && !FoundItem) //未到链表末尾且未找到节点 6 { 7 if(curr->nodeValue==target) 8 { 9 if(prev==NULL) //所删节点为头节点 10 front=front->next; 11 else 12 prev->next=curr->next; 13 delete curr; 14 FoundItem=true; 15 } 16 else 17 { 18 prev=curr; 19 curr=curr->next; 20 } 21 } 22 }
2、双指针单向链表
基本元素:单向链表的基础上加上
*back //尾指针
//各种操作与单向链表类似,加上在末尾插入数据和末尾删除,此处不一一列出
3、双向循环链表
表头(header):
只包含prev指针和next指针 无data
dlinkedlist类
1 class dnode 2 { 3 public: 4 T nodeValue; 5 dnode <T> *prev; 6 dnode <T> *next; 7 dnode(){ 8 next=this; 9 prev=this; 10 //构造表头,不含nodeValue 11 } 12 dnode(const T & value): 13 nodeValue(value) 14 { 15 next=this; 16 prev=this; 17 } 18 dnode <T> *insert (dnode <T>*curr,const T&item) 19 { 20 dnode<T> *newNode,*prevNode; 21 newNode=new dnode<T>(item); //调用有参构造函数 22 prevNode=curr->prev; 23 24 newNode->prev=prevNode; 25 newNode->next=curr; 26 prevNode->next=newNode; 27 curr->prev=newNode; 28 29 return newNode; 30 } 31 void erase(dnode<T> *curr) 32 { 33 if(curr->next==curr)//只有表头 空list 34 return; 35 36 curr->prev->next=curr->next; 37 curr->next->prev=curr->prev; 38 39 delete curr; 40 } 41 void writeDlinkedlist(dnode<T> *header)//遍历 42 { 43 dnode<T> *p=header->next; 44 while(p!=header) 45 { 46 cout<<p->nodeValue<<" "; 47 p=p->next; 48 } 49 } 50 }