LeetCode Remove Duplicates from Sorted List

2014-11-24 07:22:11 · 作者: · 浏览: 0

Remove Duplicates from Sorted List


Given a sorted linked list, delete all duplicates such that each element appear only once.

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

本题考点:

1 指针的熟练使用

2 判断重复元素

和Array的思想是一样的,不过对指针的操作增加了难度。

还是需要仔细画链表,一步一步地操作,那么这样的题目还是非常简单的。

class Solution {
public:
	ListNode *deleteDuplicates(ListNode *head) 
	{
		ListNode *cur = head;
		while (cur && cur->next)
		{
			if (cur->val == cur->next->val) cur->next = cur->next->next;
			else cur = cur->next;
		}
		return head;
	}
};


或者下面程序,效率是一样的,减少了插入操作:

ListNode *deleteDuplicates(ListNode *head) 
	{
		if (!head) return head;

		ListNode *cur = head;
		ListNode *post = head->next;
		while (cur && post)
		{
			while (post && cur->val == post->val) post = post->next;

			cur->next = post;

			cur = cur->next;
			if(post) post=post->next;
		}
		return head;
	}