SDUT_2122 数据结构实验之链表七:单链表中重复元素的删除
生活随笔
收集整理的這篇文章主要介紹了
SDUT_2122 数据结构实验之链表七:单链表中重复元素的删除
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
提交代碼
數據結構實驗之鏈表七:單鏈表中重復元素的刪除
Time Limit:?1000MS?Memory Limit:?65536KB Submit?Statistic?DiscussProblem Description
按照數據輸入的相反順序(逆位序)建立一個單鏈表,并將單鏈表中重復的元素刪除(值相同的元素只保留最后輸入的一個)。
Input
第一行輸入元素個數 n (1 <= n <= 15);
第二行輸入 n 個整數,保證在 int 范圍內。
Output
第一行輸出初始鏈表元素個數;
第二行輸出按照逆位序所建立的初始鏈表;
第三行輸出刪除重復元素后的單鏈表元素個數;
第四行輸出刪除重復元素后的單鏈表。
Example Input
10 21 30 14 55 32 63 11 30 55 30Example Output
10 30 55 30 11 63 32 55 14 30 21 7 30 55 11 63 32 14 21Hint
Author
不得使用數組! #include <iostream> using namespace std; struct node {int num;node *next; }; void display(struct node *head) {while(head!=NULL){if(head->next!=NULL)cout<<head->num<<' ';elsecout<<head->num<<endl;head=head->next;} } void Delete(struct node *head,int n) {node *p,*p1,*p2;p=head;while(p->next!=NULL)//剛遍歷到最后一個節點時就結束,不對最后一個節點進行判斷(因為在前面判斷出 前面的節點值和最后一個節點值都不想等){p1=p;//p1作為索引,在遇到與p相等的值的時候,刪除相等的節點p2=p->next;//由p后面的一個值開始進行遍歷while(p2!=NULL)//后面的值不為空節點時進行循環{if(p->num==p2->num)//在while(p2!=NULL)循環中p->num的保持不變{p1->next=p2->next;//遇到相等的值的時候索引p1的值開始發生作用p2=p2->next;//刪除節點n--;}else{p1=p1->next;//遇到不想等的時候,P1也要跟隨變化,用于在遇到相等的時候發生作用p2=p2->next;}}p=p->next;//對下一個值進行判斷}cout<<n<<endl;display(head); } void create_list(struct node *head,int n) {node *p,*q;// head=new node;head->next=NULL;for(int i=0;i<n;i++){p=new node;cin>>p->num;p->next=head->next;head->next=p;//從頭節點入手,進行中間插入,head->num并沒有值}cout<<n<<endl;display(head->next); } int main() {node *head;head=new node;int n;cin>>n;create_list(head,n);Delete(head->next,n);return 0; } 下面的段代碼一直Runtime Error#include <iostream> using namespace std; struct node {int num;node *next; }; void display(struct node *head) {while(head!=NULL){if(head->next!=NULL)cout<<head->num<<' ';elsecout<<head->num<<endl;head=head->next;} } struct node *Delete(struct node *head,int n) {node *p,*p1,*p2;p=head;while(p->next!=NULL)//剛遍歷到最后一個節點時就結束,不對最后一個節點進行判斷(因為在前面判斷出 前面的節點值和最后一個節點值都不想等){p1=p;//p1作為索引,在遇到與p相等的值的時候,刪除相等的節點p2=p->next;//由p后面的一個值開始進行遍歷while(p2!=NULL)//后面的值不為空節點時進行循環{if(p->num==p2->num)//在while(p2!=NULL)循環中p->num的保持不變{p1->next=p2->next;//遇到相等的值的時候索引p1的值開始發生作用p2=p2->next;//刪除節點n--;}else{p1=p1->next;//遇到不想等的時候,P1也要跟隨變化,用于在遇到相等的時候發生作用p2=p2->next;}}p=p->next;//對下一個值進行判斷}cout<<n<<endl;return head; } struct node *create_list(struct node *head,int n) {node *p,*q;head->next=NULL;for(int i=0;i<n;i++){p=new node;cin>>p->num;p->next=head->next;head->next=p;}return head; } int main() {node *head;head=new node;int n;cin>>n;create_list(head,n);cout<<n<<endl;display(head->next);Delete(head->next,n);display(head->next);return 0; }
總結
以上是生活随笔為你收集整理的SDUT_2122 数据结构实验之链表七:单链表中重复元素的删除的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: SDUT—2054数据结构实验之链表九:
- 下一篇: “双向链表的一些基本操作”