SDUT 2122 数据结构实验之链表七:单链表中重复元素的删除
2018-03-11 21:24
477 查看
题目
数据结构实验之链表七:单链表中重复元素的删除Time Limit: 1000 ms Memory Limit: 65536 KiB
Problem Description
按照数据输入的相反顺序(逆位序)建立一个单链表,并将单链表中重复的元素删除(值相同的元素只保留最后输入的一个)。
Input
第一行输入元素个数 n (1 <= n <= 15);
第二行输入 n 个整数,保证在 int 范围内。
Output
第一行输出初始链表元素个数;
第二行输出按照逆位序所建立的初始链表;
第三行输出删除重复元素后的单链表元素个数;
第四行输出删除重复元素后的单链表。
Sample Input
10
21 30 14 55 32 63 11 30 55 30
Sample Output
10
30 55 30 11 63 32 55 14 30 21
7
30 55 11 63 32 14 21
正确代码:
#include <stdio.h> #include <stdlib.h> struct node{ int data; struct node *next; }; void create(struct node*head,int n) { struct node *p ,*tail; tail=head; for(int i=1;i<=n;i++) { p=(struct node*)malloc(sizeof(struct node)); p->next=NULL; scanf("%d",&p->data); p->next=head->next; head->next=p; } } void show(struct node*head) { head=head->next; while(head) { if(head->next==NULL) printf("%d\n",head->data); else printf("%d ",head->data); head=head->next; } } int delete(struct node *head,int n) { struct node*p,*q,*z; p=head->next; while(p) { q=p;z=p->next; while(z) { 4000 if(z->data==p->data) { q->next=z->next; z=z->next; n--; } else { q=q->next; z=z->next; } } p=p->next; } return n; } int main() { int n; struct node*head; head=(struct node*)malloc(sizeof(struct node)); head->next=NULL; scanf("%d",&n); create(head,n); printf("%d\n",n); show(head); printf("%d\n",delete(head,n)); show(head); return 0; }
3.后记
这种方法明显比自己弄的双向链表好多了,简单多了,还很好理解,前面那个双向链表,看起来思路很简单,但其实写起来相当麻烦,而这个就简单多了。我们使用两个元素,q和z,z表示前面判断的,而q表示后面的,这样就很好实现。
你所担心的如果判断出来然后改变链表可能导致的链表混乱问题,其实用if和else就完美解决,整个内容就这么点,其实就是这个样子。
while(p) { q=p;z=p->next; while(z) { if(z->data==p->data) { q->next=z->next; z=z->next; n--; } else { q=q->next; z=z->next; } } p=p->next; }
真的是,没有对比,就永远不知道自己的代码写得有多么烂啊!
相关文章推荐
- SDUT_2122 数据结构实验之链表七:单链表中重复元素的删除
- SDUT 2122 数据结构实验之链表七:单链表中重复元素的删除
- SDUT-2122 数据结构实验之链表七:单链表中重复元素的删除
- SDUT 2122 数据结构实验之链表七:单链表中重复元素的删除
- 山东理工OJ【2122】数据结构实验之链表七:单链表中重复元素的删除
- 山东理工OJ【2122】数据结构实验之链表七:单链表中重复元素的删除(两种思想)
- sdut.acm 2012级《程序设计基础Ⅱ)》_链表 数据结构实验之链表七:单链表中重复元素的删除
- 2122数据结构实验之链表七:单链表中重复元素的删除
- 2122数据结构实验之链表七:单链表中重复元素的删除
- 山东理工OJ 2122 数据结构实验之链表七:单链表中重复元素的删除
- SDUT OJ 2122 数据结构实验之链表七:单链表中重复元素的删除
- 2122 数据结构实验之链表七:单链表中重复元素的删除
- SDUT-数据结构实验之链表七:单链表中重复元素的删除
- 数据结构实验之链表七:单链表中重复元素的删除
- 数据结构实验之链表七:单链表中重复元素的删除
- SDUT OJ 数据结构实验之链表七:单链表中重复元素的删除
- C语言 链表 数据结构实验之链表七:单链表中重复元素的删除
- 数据结构实验之链表七:单链表中重复元素的删除
- 数据结构实验之链表七:单链表中重复元素的删除
- 数据结构实验之链表七:单链表中重复元素的删除