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

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

链表中元素为键盘输入,得到删除重复元素后的结果

#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, *r;
	p = L->next;
	while (p->next)
	{
		q = p;
		while (q->next)
		{
			if (q->next->data == p->data)
			{
				r = q->next;    //重复结点,用r指向,删除r
				q->next = r->next;
				free(r);
			}
			else q = q->next;
		}
		p = p->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 · 访问量 79

猜你喜欢

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