笔试代码题--删除链表中的重复结点

笔试代码题--删除链表中的重复结点


题目描述:

删除链表中重复的节点
在一个排序,如何删除重复的节点?
例如:1 -> 2 -> 3 -> 3 -> 4
删除后是 1 -> 2 -> 4

代码如下:用三指针法:

ListNode* deleteDuplication(ListNode* pHead)
{
	// 先判断空
	if (pHead == NULL)
	{
		return NULL;
	}
	// 判断是否只有一个节点
	if (pHead->next == NULL)
	{
		return pHead;
	}
	// 我们采用带头链表,自己添加一个头
	ListNode* pre = new ListNode();
	pre->next = pHead; // 把头节点链接在链表上
	ListNode* pre_head = pre; // 用来保存头节点,用于返回删除后的链表
	ListNode* cur = pHead; //中指针
	ListNode* nex = pHead->next; // 后面指针
	while (nex != NULL) // 结束条件
		while (nex != NULL && cur->val == nex->val) 
		{
			nex = nex->next;
		}
		// 如果没有重复的那么cur的next一定等于nex
		if (cur->next != nex) // 如果相等说明没有相同的节点
		{
			while (cur != nex) // 删除动作
			{
				pre->next = cur->next;
				delete cur;
				cur = pre->next;
			}
			if (nex != NULL) // 这里一定要要注意,要防止走到NULL发生段错误
			nex = nex->next;
		}
		else
		{
			// 处理没有重复的情况
			pre = cur;
			nex = nex->next;
			cur = cur->next;
		}
	}
	ListNode* head = pre_head->next; // 释放空间,防止内存泄漏
	delete pre_head;
	return head;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值