在写完上篇后,又对单链表中去除重复的数据进行编程,以下是编写的代码
#include <stdio.h>
#include <stdlib.h>
#define N 10
struct Data{
int num;
struct Data *next;
};
struct Data * Insert()
{
int data,i;
struct Data *head,*r,*s;
head = ( struct Data * )malloc( sizeof (struct Data));
head->next = NULL;
r=head;
for (i=0; i<N; i++ )
{
scanf("%d",&data);
s = ( struct Data *)malloc(sizeof (struct Data));
s->num = data;
s->next = r->next;
r->next = s;
r=s;
}
return head;
}
void print(struct Data *head)
{
struct Data *p;
p = head->next;
printf("the list is :");
while(p!=NULL)
{
printf("%d\t",p->num);
p=p->next;
}
printf("\n");
}
struct Data *quchong(struct Data *head)
{
struct Data *p,*q,*s;
p = head->next;
while(p->next!=NULL)
{
q=p;
while(q->next!=NULL)
{
if(q->next->num == p->num)
{
s = q->next;
q->next = s->next;
free(s);
}
else
q=q->next;
}
p=p->next;
}
return head;
}
int main ( int argc , char * argv [])
{
struct Data *head;
head = Insert();
print(head);
head = quchong(head);
print(head);
}
采用上篇文章尾插法进行链表数据插入,在quchong()函数中,将链表头结点进行参数传递,该函数的思想是:
(1)首先p指向第一个结点,在第一层while循环中p控制的是原始数据结点,即要比较的数据;
(2)在第一层while循环中q=p(我曾认为应该是q=p->next,结果发现当有相同的数据存储在相邻的结点时不能正确删除,因为此时s指针的指向将发生错误,与预期不同)
(3)在第二层循环中,q控制的是目标数据结点,目标数据与原始数据的数据域相同时用指针s指向该当前目标数据结点,用s = q->next; q->next = s->next; free(s); 等语句释放当前重复的数据结点,接着q指针依次向后搜索是否还有与当前p结点数据域重复的结点;若有,循环(3)步骤;若查找到链表结尾没有则p指针指向下一结点,即跳出第二层while循环,进入第一层循环
因为本人是双系统在Linux下写的程序运行正确,现在在windows写没有办法截图,大家有不同见解的可以提出来一块学习!