對於循環雙向鏈表
判斷一個鏈表是否爲空的條件爲:head->next==head (頭指針)
判斷*p爲最後一個節點的條件爲:p->next=head
- #include<iostream>
- using namespace std;
- /*雙鏈表結構*/
- typedef struct node
- {
- int data;
- struct node *prior;
- struct node *next;
- }DNode;
- /*創建一個帶頭節點的雙鏈表*/
- void CreateDLink(DNode *&head)
- {
- int x;
- DNode *p,*s;
- s=(DNode *)malloc(sizeof(DNode));
- if(s==NULL)
- {
- cout<<"Fail to malloc the head node!"<<endl;
- }
- s->data=0;
- s->prior=NULL;
- s->next=NULL; //建立一個頭結點爲head的雙鏈表
- head=s; //若是循環雙向鏈表則爲:s->next=s->prior=s;
- cout<<"please input the data of the node"<<endl;
- cin>>x;
- while(x!=0)
- {
- p=(DNode *)malloc(sizeof(DNode));
- if(p==NULL)
- {
- cout<<"Fail to malloc a new node!"<<endl;
- }
- p->data=x;
- s->next=p;
- p->prior=s;
- p->next=NULL;
- s=p;
- cin>>x;
- }
- }
- void PrintLink(DNode *head)
- {
- if(head->next==NULL)
- {
- cout<<"The list is NULL"<<endl;
- return ;
- }
- DNode *p;
- p=head->next;
- while(p!=NULL)
- {
- cout<<p->data<<" ";
- p=p->next;
- }
- cout<<endl;
- }
- int Length(DNode *head) //求雙鏈表長度
- {
- int len=0;
- DNode * p=head->next;
- while(p!=NULL)
- {
- len++;
- p=p->next;
- }
- return len;
- }
- DNode * Get(DNode *head,int i) //獲取鏈表第i個節點地址
- {
- int j=0;
- DNode *p=head->next;
- while(j<i&&p!=NULL)
- {
- p=p->next;
- j++;
- }
- if(p!=NULL)
- return p;
- else
- return NULL;
- }
- int InsertNode(DNode *head,int x,int i)//在第i個位置插入一個節點
- {
- DNode *s,*p;
- s=(DNode *)malloc(sizeof(DNode));
- s->data=x;
- if(i==0)
- {
- s->next=head->next;
- if(head->next!=NULL)
- head->next->prior=s;
- s->prior=head;
- head->next=s;
- }
- else
- {
- p=Get(head,i-1); //查找待插入節點前一個位置
- if(p==NULL)
- return 0;
- else
- {
- s->next=p->next;
- if(p->next!=NULL)
- p->next->prior=s;
- s->prior=p;
- p->next=s;
- }
- }
- return 1;
- }
- void DeleteNode(DNode *head,int index) //刪除第index個節點
- {
- if(head->next==NULL)
- {
- cout<<"The list is NULL"<<endl;
- return;
- }
- DNode *p,*s/*保存待刪除的節點*/;
- if(index==0)
- {
- s=head->next;
- head->next=s->next;
- if(s->next!=NULL)
- s->next->prior=head;
- free(s);
- }
- else
- {
- p=Get(head,index-1);
- if(p==NULL)
- cout<<"The Node "<<index<<"is not exist"<<endl;
- else
- {
- s=p->next;
- p->next=s->next;
- if(s->next!=NULL)
- s->next->prior=p;
- free(s);
- }
- }
- }
- int main(int argc,char *argv[])
- {
- DNode *head;
- CreateDLink(head);
- cout<<"鏈表長度爲:"<<Length(head)<<endl;
- PrintLink(head);
- cout<<"第3個節點的值爲:"<<Get(head,3)->data<<endl;
- cout<<"輸入插入節點的位置及值:"<<endl;
- int value, index;
- cin>>index>>value;
- InsertNode(head,value,index);
- cout<<"插入後的鏈表爲:"<<endl;
- PrintLink(head);
- cout<<"請輸入要刪除的節點位置:"<<endl;
- cin>>index;
- DeleteNode(head,index);
- PrintLink(head);
- return 0;
- }