剑指offer——20删除链表中重复的结点

题目描述

在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,返回链表头指针。 例如,链表1->2->3->3->4->4->5 处理后为 1->2->5
 
题解:
  这道题没什么讲的,注意指向空的边界就行,新建一个头节点更容易处理。
 
 1 class Solution {
 2 public:
 3     ListNode* deleteDuplication(ListNode* pHead)    {
 4         if (pHead == nullptr || pHead->next == nullptr)return pHead;
 5         ListNode *newHead = new ListNode(0);
 6         newHead->next = pHead;
 7         ListNode *pre = newHead, *p = newHead->next;
 8         int sameNum = 0;
 9         while (p!= nullptr && p->next != nullptr)
10         {
11             if (p->val == p->next->val)
12             {
13                 sameNum = p->val;
14                 while (pre->next != nullptr && pre->next->val == sameNum)
15                     pre->next = pre->next->next;
16                 p = pre->next;
17             }
18             else
19             {
20                 pre = p;
21                 p = p->next;
22             }
23         }
24         return newHead->next;
25     }
26 };

 

posted @ 2019-10-11 22:39  自由之翼Az  阅读(111)  评论(0编辑  收藏  举报