顺序表应用2:多余元素删除之建表算法
Time Limit: 3 ms Memory Limit: 600 KiB
Submit Statistic
Problem Description
一个长度不超过10000数据的顺序表,可能存在着一些值相同的“多余”数据元素(类型为整型),编写一个程序将“多余”的数据元素从顺序表中删除,使该表由一个“非纯表”(值相同的元素在表中可能有多个)变成一个“纯表”(值相同的元素在表中只保留第一个)。
要求:
1、必须先定义线性表的结构与操作函数,在主函数中借助该定义与操作函数调用实现问题功能;
2、本题的目标是熟悉在顺序表原表空间基础上建新表的算法,要在原顺序表空间的基础上完成完成删除,建表过程不得开辟新的表空间;
3、不得采用原表元素移位删除的方式。
Input
第一行输入整数n,代表下面有n行输入;
之后输入n行,每行先输入整数m,之后输入m个数据,代表对应顺序表的每个元素。
Output
输出有n行,为每个顺序表删除多余元素后的结果
Sample Input
4
5 6 9 6 8 9
3 5 5 5
5 9 8 7 6 5
10 1 2 3 4 5 5 4 2 1 3
Sample Output
6 9 8
5
9 8 7 6 5
1 2 3 4 5
Hint
Source
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *next;
};
struct node creat_list(int n)
{
struct node *head, *p, *q;
head = (struct node *)malloc(sizeof(struct node ));
head ->next = NULL;
p = head;
int i;
for (i = 0 ; i < n ; i++)
{
q = (struct node *)malloc(sizeof(struct node ));
scanf("%d", &q->data);
p ->next = q;
q ->next = NULL;
p = q;
}
return *head;
}
void dele(struct node *head)
{
struct node *p, *q, *x;
p = head ->next;
while(p ->next != NULL)
{
x = p;
q = p->next;
while(q != NULL)
{
if (q ->data == p ->data && q ->next != NULL)
{
x ->next = q ->next;
free(q);
q = x ->next;
}
else if (q ->data == p ->data && q ->next == NULL)
{
x ->next = NULL;
q = NULL;
}
else
{
x = q;
q = q ->next;
}
}
if (p ->next != NULL)
p = p->next;
}
}
int main()
{
int n, m ;
struct node *head1;
scanf("%d", &m);
while(m--)
{
scanf("%d", &n);
head1 = (struct node *)malloc(sizeof(struct node)) ;
*head1 = creat_list(n);
dele(head1);
struct node *p;
p = head1 ->next;
while(p != NULL)
{
if (p ->next != NULL)
{
printf("%d ", p->data);
}
else
{
printf("%d\n", p->data);
}
p = p->next;
}
}
return 0;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)