leetcode 删除有序链表中的重复元素

问题描述:

https://oj.leetcode.com/problems/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.

问题分析:

基本问题,有序的单链表所有的重复元素都集中在一起,虽然含有重复元素但是每个元素都要保留

所以识别重复元素比较容易,该题也就容易解答。只需要建立一个新的表头就可以很容易的解决该问题。

链表的识别: cur->val == tail->val ?  duplicate : distinct.

初始条件的设定:

示例代码:

ListNode *deleteDuplicates(ListNode *head) 
    {
        ListNode node(0), *tail, *p, *cur;
        if (!head || !head->next)
        {
            return head;
        }
        node.next = head;
        tail = head;
        p = head->next;
        while (p)
        {
            cur = p; p = p->next;
            if (cur->val != tail->val)
            {   tail->next = cur; tail = cur;   }
            else
            {   delete cur;   }
        }
        tail->next = NULL;
        return node.next;
    }

问题描述:

有序的单链表删除链表中重复元素只保留出现一次的元素。

https://oj.leetcode.com/problems/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.

问题分析:

需要先识别出重复元素再删除,识别重复元素如下
ListNode *p = head;
(p && p->next && p->val == p->next->val) ? duplicate : distinct
{ /* p->val 是重复元素 */ }

示例代码:

ListNode *start, *end;
start = end = head; 
bool duplicate = false;
ListNode node, *tail = &node;
while (end)
{
    while (start->val == end->val) /* 识别重复元素 */
    { 
     end = end->next;
     if (end->val == start->val)
	 {	duplicate = true;	}
    }
    if (duplicate) /* 对重复元素的处理 */
	{
		while (start != end)
		{ cur = start; start = start->next; delete cur;  }
	}
    else { tail->next = start; tail = start; start = start->next; }
}
return node.next;

以上代码中有严重的bug

修正如下:

ListNode *deleteDuplicates(ListNode *head) 
    {
        if (!head || !head->next)
        {
            return head;
        }
        ListNode *p = head;
        ListNode node(0), *tail = &node;
        while (p->next)
        {
            if (p->val == p->next->val) /* 重复元素的处理:找出所有的重复元素,略过 */
            {
                int v = p->val; 
                p = p->next->next;
                for (; p && p->val == v; p = p->next);
                if (!p) return node.next;
            }
            else  /* 单一元素添加到新表中 */
            {
                tail->next = p; tail = p;
                p = p->next;
                tail->next = NULL;
            }
           
        }
        tail->next = p;
        return node.next;
    }




你可能感兴趣的:(基本算法)