/*
已知带头结点的单链表la={a1,a2,…an},试编写一个算法
将值重复的结点删除,使所得的结果表中的值均不相同。
*/
# include <iostream>
# include <stdlib.h>
# include <stdio.h>
using namespace std;
typedef struct Node
{
int elem;
struct Node *next;
}*Linklist;
void inlinklist(Linklist &l, int n)
{
l = (Linklist)malloc(sizeof(Node));
l->next = NULL;
Linklist p, END;//定义尾部节点
END = l;
printf("请输入想要创建的链表元素:\n");
for(int i = 0; i < n; i++)
{
p = (Linklist)malloc(sizeof(Node));
scanf("%d", &p->elem);
END -> next = p;
p->next = NULL;
END = p;
}
}
void outlinklist(Linklist l)
{
printf("链表中的值为:\n");
Linklist p;
p = l->next;
while(p != NULL)
{
printf("%d ", p->elem);
p = p->next;
}
printf("\n");
}
void delete_repeat(Linklist &l)
{
Linklist p, q, s;
p = l;
while(p)
{
q = p;
while(q->next)
{
if(q->next->elem == p->elem)
{
s = q->next;
q->next = s->next;
free(s);
}
else
{
q = q->next;
}
}
p = p->next;
}
}
int main()
{
Linklist l;
int n;
printf("请输入链表的元素个数:\n");
scanf("%d", &n);
inlinklist(l, n);
delete_repeat(l);
outlinklist(l);
return 0;
}