• 剑指offer56:删除链表中重复的结点,排序的链表中,删除重复的结点不保留,返回链表头指针。 例如,链表1->2->3->3->4->4->5 处理后为 1->2->5


    1 题目描述

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

    2 思路和方法

      (1)链表为空,return NULL

      (2)头结点存在重复(1122345),删除头结点,另选新的结点作为头结点。处理这种特殊情况,多申请一个指针就可以了。

    3 C++核心代码

     1 /*
     2 struct ListNode {
     3     int val;
     4     struct ListNode *next;
     5     ListNode(int x) :
     6         val(x), next(NULL) {
     7     }
     8 };
     9 */
    10 class Solution {
    11 public:
    12     ListNode* deleteDuplication(ListNode* pHead)
    13     {
    14         if (pHead==NULL)
    15             return NULL;
    16         if (pHead!=NULL && pHead->next==NULL)
    17             return pHead;
    18 
    19         ListNode* current;    //新建一个节点,防止头结点要被删除
    20 
    21         if ( pHead->next->val==pHead->val){
    22             current=pHead->next->next;//指针赋值,就相当于删除
    23             while (current != NULL && current->val==pHead->val)
    24                 current=current->next;
    25             return deleteDuplication(current);
    26         }
    27         else {
    28             current=pHead->next;
    29             pHead->next=deleteDuplication(current); //返回头结点的下一个节点
    30             return pHead;
    31         }
    32     }
    33 };
    View Code

    参考资料

    https://blog.csdn.net/hellozex/article/details/81087592

    链表知识点:https://blog.csdn.net/qq_33835307/article/details/82683475,https://blog.csdn.net/slandarer/article/details/91863177,https://blog.csdn.net/ccblogger/article/details/81176338

  • 相关阅读:
    jq---方法总结
    Coderfroces 862 B . Mahmoud and Ehab and the bipartiteness
    Coin
    joisino's travel
    日天的终生大事(dp)
    Codefroces 852 G. Bathroom terminal
    Codefroces432 div2 A,B,C
    Atcoder ABC 069 C
    Codefroces 849 A,B
    HDU 6186 CS Course
  • 原文地址:https://www.cnblogs.com/wxwhnu/p/11429134.html
Copyright © 2020-2023  润新知