/* ============================================================================ Name : Circular link.cpp Author : ntsk13 [email protected] Version : Copyright : GPL Description : double Link list study, complement by C++ Date : 2015.06.16 ============================================================================ */ #include <iostream> using namespace std; typedef struct { int data; }Elem_t; typedef struct lnode{ Elem_t e; struct lnode * last;//指向上一个节点 struct lnode * next;//指向下一个节点 }node,*pnode; class Link { public: void init(pnode & L); void clear(pnode & L); int get_length(pnode &L); Elem_t get_elem(pnode &L,int i); void traverse(pnode &L); void insert(pnode &L,Elem_t e,int i); void delete_elem(pnode &L,int i); }; int main(void) { pnode H=NULL;//head p Elem_t zero,one,two,three,four,five; zero.data=0; one.data=1; two.data=2; three.data=3; four.data=4; Link list; list.init(H); list.insert(H,zero,0); list.insert(H,one,1); list.insert(H,two,2); list.insert(H,three,3); list.insert(H,four,4); list.traverse(H); cout<<"len is "<<list.get_length(H)<<endl; five=list.get_elem(H,4); cout<<"================================="<<endl; cout<<"five is "<<five.data<<endl; list.delete_elem(H,4); cout<<"================================="<<endl; list.traverse(H); cout<<"len is "<<list.get_length(H)<<endl; list.insert(H,two,0); list.insert(H,five,2); cout<<"================================="<<endl; list.traverse(H); cout<<"len is "<<list.get_length(H)<<endl; return 0; } void Link::init(pnode & L) { L=new node;//构造一个头结点 (L->e).data =0;//头结点的data作为长度 L->last=NULL; L->next=NULL; } void Link::clear(pnode & L) { int i=0; pnode p=L; pnode tmp=NULL; int len=(L->e).data; for(i=0;i<len;i++) { tmp=p->next; delete p; p=tmp; } L=NULL; } int Link::get_length(pnode & L) { return (L->e).data;; } Elem_t Link::get_elem(pnode & L,int i) { int j=0; pnode p=L->next; while(j <i ) { j++; p=p->next; } return p->e; } void Link::traverse(pnode & L) { int i=0; pnode p=L->next;//避免把头指针元素输出 /* 1) 以长度作为循环链表是否结束的依据 * int len= (L->e).data; for(i=0;i< len;i++) { cout<<"The "<<i<<"th elem is "<<(p->e).data<<endl; p=p->next; } */ //2)以 next 指针指向 NULL 作为结束标识 while(p != NULL) { cout<<"The "<<i<<"th elem is "<<(p->e).data<<endl; p=p->next; } } void Link::insert(pnode & L,Elem_t e,int i)// before i insert { int j=0; pnode p=L; pnode tmp=NULL; for(j=0;j< i;j++) { p=p->next; } tmp=new node; (tmp->e).data=e.data; tmp->next=p->next; tmp->last=p; p->next=tmp; ( L->e).data++; } void Link::delete_elem(pnode & L,int i) { int j=0; pnode p=L->next; pnode tmp=NULL; int len=get_length(L); if(i == len-1)//删掉的节点是最后一个节点 { for(j=0;j< i-1;j++) { p=p->next; } tmp=p->next;//将要被free的节点 p->next=p->next->next;//下一节点指向 下下一节点 (L->e).data--;//长度减一 delete tmp; return ; } ///删掉的节点不是最后一个节点 for(j=0;j< i-1;j++) { p=p->next; } tmp=p->next;//将要被free的节点 p->next=p->next->next;//下一节点指向 下下一节点 tmp->next->last=p; (L->e).data--;//长度减一 delete tmp; }