删除链表中重复元素

//删除链表中重复的元素
//比如1 2 3 3 4 4
//删除重复元素变为1 2

#include <iostream>
using namespace std;

struct Node
{
	Node(int x)
	{
		value = x;
		next = NULL;
	}
	int value;
	Node *next;
};
void deleteDuplication(Node **head)
{
	if (head == NULL || *head == NULL)
		return;

	Node *pre = NULL;//当前节点前面的那个不重复节点,比如2就是一个不重复节点
	Node *cur = *head;

	while (cur)
	{
		bool needDelete = false;

		if (cur->next && cur->value == cur->next->value)
			needDelete = true;

		if (!needDelete)//出现了不重复的节点
		{
			pre = cur;
			cur = cur->next;
		}

		else
		{
			int value = cur->value;
			Node *pNext = NULL;//这里不能直接pNext=cur->next,因为cur有可能为空
			while (cur && cur->value == value)
			{
				pNext = cur->next;//保留cur的下一个节点
				delete cur;
				cur = pNext;
			}
			if (pre == NULL)//说明还没出现不重复的节点
				*head = cur;
			else
				pre->next = cur;//将不重复的节点连接到当前节点
		}
	}
}

void print(Node *head)
{
	while (head)
	{
		cout << head->value << " ";
		head = head->next;
	}
	cout << endl;
}

int main()
{
	Node *p1 = new Node(1);
	Node *p2 = new Node(2);
	Node *p3 = new Node(3);
	Node *p4 = new Node(3);
	Node *p5 = new Node(4);
	Node *p6 = new Node(4);

	p1->next = p2;
	p2->next = p3;
	p3->next = p4;
	p4->next = p5;
	p5->next = p6;

	print(p1);
	deleteDuplication(&p1);
	print(p1);

	return 0;
}


                
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
你好!如果你要用 C 语言编写一个删除链表重复元素的算法,可以按照以下步骤进行: 1. 定义链表结构体 首先,你需要定义链表结构体,包括链表节点的值和指向下一个节点的指针。比如: ``` struct ListNode { int val; struct ListNode* next; }; ``` 2. 定义删除函数 接着,你需要定义一个函数,用于删除链表重复元素。该函数的输入是链表头指针,输出是删除重复元素后的链表头指针。你可以按照以下思路编写该函数: - 定义一个指针p,指向链表节点。 - 遍历链表,如果当前节点的值和下一个节点的值相等,说明当前节点重复元素,需要将其从链表删除。 - 删除重复元素的方法是将当前节点的next指针指向下一个节点的next指针,然后释放下一个节点。 - 如果当前节点不是重复元素,将p指向下一个节点,继续遍历。 代码实现如下: ``` struct ListNode* deleteDuplicates(struct ListNode* head) { struct ListNode* p = head; while (p != NULL && p->next != NULL) { if (p->val == p->next->val) { struct ListNode* tmp = p->next; p->next = tmp->next; free(tmp); } else { p = p->next; } } return head; } ``` 3. 调用删除函数 最后,你可以在主函数创建链表并调用删除函数。比如: ``` int main() { struct ListNode* node1 = (struct ListNode*)malloc(sizeof(struct ListNode)); node1->val = 1; struct ListNode* node2 = (struct ListNode*)malloc(sizeof(struct ListNode)); node2->val = 1; struct ListNode* node3 = (struct ListNode*)malloc(sizeof(struct ListNode)); node3->val = 2; struct ListNode* node4 = (struct ListNode*)malloc(sizeof(struct ListNode)); node4->val = 2; node1->next = node2; node2->next = node3; node3->next = node4; node4->next = NULL; struct ListNode* new_head = deleteDuplicates(node1); // 遍历新链表,输出元素 struct ListNode* p = new_head; while (p != NULL) { printf("%d ", p->val); p = p->next; } return 0; } ``` 该程序的输出结果为:1 2 希望这个答案对你有帮助!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值