一【题目类别】
二【题目来源】
- 本题目选自王道2023考研计算机数据结构复习指导40页中二、综合应用题之12题
三【题目描述】
- 在一个递增有序的线性表中,有数值相同的元素存在。若存储方式为单链表,设计算法去掉数值相同的元素,使表中不再有重复的元素,例如(7,10,10,21,30,42,42,42,51,70)将变为(7,10,21,30,42,51,70)。
四【解题思路】
五【时间频度】
- 时间复杂度:
O
(
n
)
O(n)
O(n),其中
n
n
n为单链表长度
- 空间复杂度:
O
(
1
)
O(1)
O(1)
六【代码实现】
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
typedef struct LNode
{
int data;
struct LNode* next;
}Node, *Link;
void PrintLink_Del_Same(Link link)
{
Node* p = link->next;
while (p != NULL)
{
if (p->next != NULL)
{
printf("%d->", p->data);
}
else
{
printf("%d", p->data);
}
p = p->next;
}
}
void Del_Same(Link L)
{
Link p = L->next;
Node* temp = (Node*)malloc(sizeof(Node));
if (p == NULL)
{
return;
}
while (p->next != NULL)
{
temp = p->next;
if (p->data == temp->data)
{
p->next = temp->next;
free(temp);
}
else
{
p = p->next;
}
}
}
int main()
{
Link link = (Link)malloc(sizeof(Node));
link->next = NULL;
Node* p = link;
int len;
printf("请输入单链表的长度:");
scanf("%d", &len);
printf("请输入单链表的元素:");
for (int i = 0; i < len; i++)
{
int x;
scanf("%d", &x);
Node* temp = (Node*)malloc(sizeof(Node));
temp->data = x;
temp->next = NULL;
p->next = temp;
p = temp;
}
printf("初始单链表为:");
PrintLink_Del_Same(link);
printf("\n");
Del_Same(link);
printf("删除重复元素后的单链表为:");
PrintLink_Del_Same(link);
printf("\n");
system("pause");
return 0;
}
七【程序测试】
