[剑指offer] 56. 删除链表中重复的结点

题目描述

在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,返回链表头指针。 例如,链表1->2->3->3->4->4->5 处理后为 1->2->5

思路:
 

class Solution
{
  public:
    ListNode *deleteDuplication(ListNode *pHead)
    {
        if (pHead == NULL || pHead->next == NULL)
            return pHead;

        ListNode *head = new ListNode(pHead->val - 1);
        head->next = pHead;

        ListNode *p = head;
        ListNode *q = head->next;
        while (q)
        {
            while (q->next && (q->next->val == q->val))
            {
                q = q->next;
            }
            if (p->next != q)
            {
                q = q->next;
                p->next = q;
            }
            else
            {
                p = q;
                q = q->next;
            }
        }
        return head->next;
    }
};

猜你喜欢

转载自www.cnblogs.com/ruoh3kou/p/10240264.html
今日推荐