zoukankan      html  css  js  c++  java
  • 剑指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 };
  • 相关阅读:
    对我影响最大的三位老师
    自我介绍
    第二周作业
    2019第一次作业
    PTA编程总结3
    币值转换
    PTA编程总结2
    PTA编程总结1
    秋季学期学习总结
    人生路上对你影响最大的三位老师
  • 原文地址:https://www.cnblogs.com/zzw1024/p/11657470.html
Copyright © 2011-2022 走看看