要求:
构建一个单链表,值是从小到大排序,且存在重复的值。设计算法,删除表中值相同的多余元素,使得操作后表中的所有元素值均不相同,同时释放被删除的结点空间。
#include <stdio.h>
int nodeNum = 5;
struct node
{
int t;
node * link;
};
//建表
struct node *creatlist()
{
int i = 0;
int t;
struct node *head, *p, *q;
//头结点
scanf_s("%d", &t);
head = new struct node;
head->t = t;
head->link = 0;
q = head;
for (i = 0; i < nodeNum - 1; i++) {
scanf_s("%d", &t);
p = new struct node;
p->t = t;
p->link = 0;
q->link = p;
q = q->link;
}
return head;
}
//删除
struct node *deleteSameNode(struct node *head)
{
if (head == 0) {
printf("这是个空表\n");
return head;
}
struct node *p, *q;
p = head;
while (p->link != 0)
{
while (p->t == p->link->t) {
q = p->link;
p->link = q->link;
delete q;
if (p->link == 0) {
return head;
}
}
p = p->link;
}
return head;
}
//打印
void print(struct node *head)
{
struct node *tmp;
tmp = head;
while (tmp != NULL)
{
printf("%d ", tmp->t);
tmp = tmp->link;
}
printf("\n");
}
//释放
void removeAll(struct node *head)
{
struct node *p = head;
while (head != 0) {
p = head;
head = head->link;
delete p;
}
}
int main()
{
struct node *head = NULL;
//创建单链表
printf("输入5个值\n");
head = creatlist();
print(head);
//删除多余节点
head = deleteSameNode(head);
//打印单链表
printf("删除后的链表为:\n");
print(head);
//释放
removeAll(head);
return 0;
}
版权声明:本文为m0_52341601原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。