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
Hint
Source
不得使用数组!
链表中的元素删除与数组的元素删除不同,数组中的元素删除要将元素全部前移或后移,但是链表中的元素是要改变要删除元素前的节点的指针指向,但要注意改变的顺序,先改变前面的只想要删除节点指针指向的节点,在释放删除节点,也可以不释放
#include <stdio.h>
#include <stdlib.h>
struct node
{
int a;
struct node *next;
};
//定义节点形式;
struct node* fun(struct node *head,struct node *end,int a1)//链表建立函数,即插入节点;
{
struct node *p;
p = (struct node*)malloc(sizeof(struct node));
p -> a = a1;
p -> next = head->next;
head -> next =p;
return 0;
}
void show(struct node *head,int n) //定义一个链表输出函数,在下面直接调用就行,这样是程序更清晰;
{
struct node *p;
p = head -> next;
printf("%d\n",n);
while(p)
{
if(p->next)
printf("%d ",p->a);
else printf("%d\n",p->a);
p = p -> next;
}
}
int main()
{
int n,a1,i;
struct node *head,*end;
scanf("%d",&n);
head = (struct node*)malloc(sizeof(struct node)); //定义一个头节点;
scanf("%d",&a1);
end = (struct node*)malloc(sizeof(struct node)); //定义一个尾节点;
head -> next = end;
end -> a = a1;
end -> next = NULL;
for(i=n-1; i>0; i--) //建立链表;
{
scanf("%d",&a1);
fun(head,end,a1);
}
show(head,n); //输出;
struct node *p1,*q1,*r;
p1=head->next;
q1=p1;
while(p1) //每一个节点都要和其后面的每一个节点比较;
{
while(q1->next)
{
if(p1->a==q1->next->a) //如果节点数据相同,执行下面删除语句;
{
r=q1->next;
q1->next=r->next;
free(r); //释放删除节点;
n--;
}
else
q1=q1->next;
}
p1=p1->next;
q1=p1;
}
show(head,n);
return 0;
}