生活随笔
收集整理的這篇文章主要介紹了
EOJ_1007_环形双向链表
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
這個環形鏈表有個恒定不變的head,head->data表示鏈表中的元素個數,缺點在于每刪除head->next,要把head->next=head->next->next要有習慣寫newNode
#include <bits/stdc++.h>
using namespace std;
//link的head->data=n結點的個數
//雖然是雙向,但是并沒有用到雙向
//不過在刪除的時候可以用到,可以直接找要刪除的元素
typedef struct node
{int data;node* next;node* pre;
}node;node* newNode(int i)
{node* tmp = new node;tmp->data = i;tmp->next=NULL;tmp->pre=NULL;return tmp;
}node* creatLink(node* head)
{head = newNode(0);//head->data鏈表元素有多少個node* p = head;while(1){int num;cin>>num;if(num==-1) break;node* tmp = newNode(num);p->next = tmp;tmp->pre = p;p = p->next;(head->data)++;}if(head->next==NULL) {return head;}p->next = head->next;//前面一直是構造非環形鏈表,最后構造完后再把尾指針指向頭指針即可head->next->pre = p;return head;
}node* deleteLink(node* head)
{while(1){node* p = head->next;int num;cin>>num;if(num==-1) break;int flag=1;int deletenum = head->data;for(int i=0;i<deletenum;i++){if(p->data==num){if(p==head->next){head->next=p->next; //當要刪除的元素是head->next時,還要把head->next修改//要注意判斷條件不能只是i==0,因為當i==1,2...的時候,也可能會刪除head->next的元素}p->next->pre = p->pre;p->pre->next = p->next;flag=0;(head->data)--;}p=p->next;}if(flag) cout<<-1<<endl;}return head;
}void print(node* head)
{if(head->data==0) return;node* p = head->next;for(int i=0;i<(head->data);i++){cout<<p->data<<" ";p = p->next;}
}int main()
{node* head;head = creatLink(head);head = deleteLink(head);print(head);return 0;
}
總結
以上是生活随笔為你收集整理的EOJ_1007_环形双向链表的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。