数据结构实验之链表七:单链表中重复元素的删除
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
Source
不得使用数组!
#include <stdio.h>
#include <stdlib.h>
int count = 0;
struct node
{
int data;
struct node *next;
};
struct node * reverse_creat(int);
void list_delete(struct node *);
void output_list(struct node *);
int main()
{
int n;
struct node *head;
scanf("%d", &n);
count = n;
head = reverse_creat(n);
printf("%d\n", count);
output_list(head);
list_delete(head);
printf("%d\n", count);
output_list(head);
return 0;
}
struct node *reverse_creat(int n)
{
int i;
struct node *head, *p;
head = (struct node *)malloc(sizeof(struct node));
head->next = NULL;
for(i = 1; i <= n; i++)
{
p = (struct node *)malloc(sizeof(struct node));
scanf("%d", &p->data);
p->next = head->next;
head->next = p;
}
return head;
}
void list_delete(struct node *head)
{
struct node *p, *q1, *q2;///定义左边指针 p ,右边比较指针 q2 ,删除用指针 q1
p = head->next;
while(p != NULL)///当 p 为空,即 p 遍历到链表末尾时,结束循环
{///等于 while(p)
q1 = p;///重置 q1 位置
q2 = q1->next;///重置 q2 位置
while(q2 != NULL)///当 q2 为空,即 q2 遍历到链表末尾时,结束循环
///此处重点!!!一定要以后面的指针 p2 为主体进行判断是否结束此轮循环
///如果以 q1 为主体判断是否结束循环就很容易令 q2 越界
{
if(p->data == q2->data)///当 p 的数据域等于 q2 的数据域时
{
q1->next = q2->next;///令 q1 的指针域指向 q2 的下一个结点
free(q2);///释放 q2 所指向的内存空间
q2 = q1->next;///令 q2 指向 q1 新的下一个结点
count--;///每完成一次删除,链表元素个数减少1
}
else
{///当 两个指针的数据域数据不同时,令 q1 和 q2 向后移位
q1 = q1->next;
q2 = q2->next;
}
}
p = p->next;///q2 每次遍历完链表后 p 都后移
}
}
void output_list(struct node *head)
{
struct node *p;
p = head->next;
while(p)
{
if(p == head->next)
printf("%d", p->data);
else
printf(" %d", p->data);
p = p->next;
}
printf("\n");
}
注意:
1. 遍历链表查找重复元素的内层循环: while(q2 != NULL)
此处重点!!!一定要以后面的指针 p2 为主体进行判断是否结束此轮循环,如果以 q1 为主体判断是否结束循环就很容易令 q2 越界
链表中与 while(p) 相关的循环一定要注意越界问题!一定要以位于后方的指针为判断条件!