LeetCdoe Remove Duplicates from Sorted List II移掉重复链表中的元素

Remove Duplicates from Sorted List II

 

Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.

For example,
Given 1->2->3->3->4->4->5, return 1->2->5.
Given 1->1->1->2->3, return 2->3.

是重复的元素就全部移掉,前面有一道是移掉多余的重复元素,保留一个。

这道题的关键就需要注意保存重复元素的前一个指针,这样才能移除元素。

考指针和链表的操作熟练程度。

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
	ListNode *deleteDuplicates(ListNode *head) 
	{
		if (!head || !head->next) return head;
		ListNode dummy(-1);	
		dummy.next = head;
		ListNode *pre = &dummy;
		ListNode *cur = head;
		ListNode *post = head->next;
		bool flag = false;

		while (cur && post)
		{
			while (post && cur->val == post->val)
			{
				post = post->next;
				flag = true;
			}
			if (flag == true) pre->next = post;
			else pre = pre->next;

			flag = false;
			cur = post;
			if (post) post = post->next;
		}
		//不能用return head, 因为如果head重复的话,需要删掉head,但是其实head还在内存中,没有删掉,不过改变了dummy->next的链表。
		return dummy.next;
	}
};


//2014-2-13 update
	ListNode *deleteDuplicates(ListNode *head) 
	{
		if (!head || !head->next) return head;
		ListNode dummy(0);
		ListNode *p = &dummy;
		bool repeat = false;
		for ( ;head->next; head = head->next)//记得步进head
		{
			if (head->val == head->next->val) repeat = true;
			else 
			{
				if (repeat) repeat = false;
				else//不重复的才加入新的链表中
				{
					p->next = head;
					p = p->next;
				}
			}
		}
		if (!repeat)//注意别漏掉
		{
			p->next = head;
			p = p->next;
		}
		p->next = nullptr; //注意:删除结尾多余的节点。
		return dummy.next;
	}








  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值