单链表中重复元素的删除

来源:互联网 发布:淘宝联盟双十一能用吗 编辑:程序博客网 时间:2024/05/16 11:33
数据结构实验之链表七:单链表中重复元素的删除
Time Limit: 1000MS Memory limit: 65536K
题目描述
按照数据输入的相反顺序(逆位序)建立一个单链表,并将单链表中重复的元素删除(值相同的元素只保留最后输入的一个)。
输入
第一行输入元素个数n;
第二行输入n个整数。
输出
第一行输出初始链表元素个数;
第二行输出按照逆位序所建立的初始链表;
第三行输出删除重复元素后的单链表元素个数;
第四行输出删除重复元素后的单链表。
示例输入
10
21 30 14 55 32 63 11 30 55 30
示例输出
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>typedef struct node{int data;struct node*next;} Node;Node *create_linkedlist(int n);void show(Node *head);Node* pure(Node *head);int main(){int n;int num;Node *head;scanf("%d",&n);head = create_linkedlist(n);num = get_linkedlist_number(head);printf("%d\n",num);show(head);head = pure(head);num = get_linkedlist_number(head);printf("%d\n",num);show(head);return 0;}Node *create_linkedlist(int n){Node *head;Node *p;int key;head = (Node*)malloc(sizeof(Node));head->next = NULL;while(n--){scanf("%d",&key);p = (Node*)malloc(sizeof(Node));p->data = key;p->next = head->next;head->next = p;}return head;}void show(Node *head){Node *p;p = head->next;while(p){    if(p->next!=NULL)    printf("%d ",p->data);else            printf("%d",p->data);p = p->next;}printf("\n");}Node* pure(Node *head){Node *p,*q,*r,*trace;/* p 用来遍历整个链表的节点   q 用来遍历p所指节点之后的节点,判断与p->data是否相等   trace 用来追踪所找到重复元素的前驱节点  */p = head->next;while(p)    {        q = p->next;trace = p;        while(q)        {/*开始我用if(q->data == p->data),发现怎么也解决不了追踪问题*/            if(q->data != p->data)            {                trace = q;q = q->next;            }else{r = q;trace->next = q->next;q = q->next;//1free(r);//2}        }        p = p->next;    }return head;}int get_linkedlist_number(Node *head){    int num = 0;    Node *p;    p = head->next;    while(p)    {        num++;        p = p->next;    }    return num;}

0 0
原创粉丝点击