@【数据结构】(单链表删除相同元素)

@【数据结构】(单链表删除相同元素)

单链表作非递减有序线性表的存储结构。请设计一个时间复杂度为O(n)的算法,删除表中所有数值相同的多余元素,并释放结点空间。

#include<stdio.h>
#include<iostream>
using namespace std;
typedef struct list
{
	int data;
	struct list *next;
}*LIST, LNode;
void InitList(LIST *L)	/* 初始化链表 */
{
	*L = (LNode *)malloc(sizeof(LNode));   //带头结点的链表初始化
	(*L)->next = NULL;
}
void Deletedup(LIST L)   //删除重复元素
{
	LNode *p, *q;
	p = L->next; 
	q = p->next;
	while (q)
	{
		if (p->data == q->data)
		{
			p->next = q->next;
			q = p->next;
		}
		else { p = p->next;
		     q = q->next;}
	}
}
LIST CreateList(LIST L)
{
	LNode *R;
	int x;
	R = L;
	cout << "请输入非递减有序数列,输入-1 结束:" << endl;
	cin >> x;
	while (x != -1)
	{
		R->next = (LNode *)malloc(sizeof(LNode));
		R->next->data = x;
		R = R->next;
		cin >> x;
	}
	R->next = NULL;
	return L;
}
void OutputList(LIST L)
{
	LNode *p;
	p = L->next;
	while (p)
	{
		cout << p->data << "  ";
		p = p->next;
	}
}
void main()
{
	LIST L;
	InitList(&L);
	CreateList(L);
	cout << "非递减有序线性表为:" << endl;
	OutputList(L);
	cout << endl;

	Deletedup(L);
	cout << "非递减有序线性表删除数值相同的多余元素后为:" << endl;
	OutputList(L);
	cout << endl;
	system("pause");
}


测试示例:
在这里插入图片描述

发布了20 篇原创文章 · 获赞 1 · 访问量 81

猜你喜欢

转载自blog.csdn.net/gsgs1234/article/details/104844241