zoukankan      html  css  js  c++  java
  • 剑指offer 删除链表中重复的结点

    题目描述

    在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,返回链表头指针。 例如,链表1->2->3->3->4->4->5 处理后为 1->2->5
     
    思路:1、dummy结点的写法是,dummy -> next 等于head,然后将head等于dummy,修改后就是dummy -> next等于原来的head结点,head指向的是dummyNode。最开始的操作都是操作dummy -> next,不要直接操作dummy。
    2、使用一个tmp进行删除操作,要注意应该是保存相同的value值,不要保存结点
    3、要将pHead -> next != nullptr写在前面,因为pHead -> next 可能为空,这时候取val就会指针越界。逻辑表达式先判断前面的,前面的逻辑false就不会判断后面的表达式了。
    while(pHead -> next != nullptr && tmp == pHead -> next  -> val){
    pHead -> next = pHead -> next -> next; }
    4、开始自己认为没有删除操作,其实联想head = head -> next,此时head就等于下一个结点了,所以上面的while循环过后,pHead -> next等于循环之后的那个结点。有if一定要写相应的else语句。
    5、最开始的pnode==nullptr就返回的时候,不要直接写nullptr,应该写return pNode;
     
     1 class Solution {
     2 public:
     3     ListNode* deleteDuplication(ListNode* pHead){
     4         if(pHead == nullptr || pHead -> next == nullptr){
     5             return pHead;
     6         }
     7         //ListNode* cur = pHead;
     8          
     9         ListNode* dummyNode = new ListNode(-1);
    10         dummyNode -> next = pHead;
    11         pHead = dummyNode;
    12          
    13         int tmp;
    14           
    15         while(pHead -> next != nullptr && pHead -> next -> next != nullptr){
    16             if(pHead -> next -> val == pHead -> next -> next -> val){
    17                 tmp = pHead -> next -> val;
    18                 while(pHead -> next != nullptr && tmp == pHead -> next  -> val){
    19                     pHead -> next = pHead -> next -> next;
    20                 } 
    21                  
    22             }
    23             else{               
    24                 pHead  = pHead -> next;
    25             }
    26              
    27         }
    28         return dummyNode -> next;
    29     }
    30 };
  • 相关阅读:
    Verilog手绘FVH信号
    Verilog编码规范与时序收敛
    关于DDS的基础知识
    阅读ug949-vivado-design-methodology笔记
    在windows系统上使用pip命令安装python的第三方库
    pandas第一课
    视频外同步信号研究---fvh
    FPGA调试技巧
    关于FIFO异步复位的问题
    搭建一个microblaze的最小系统
  • 原文地址:https://www.cnblogs.com/dingxiaoqiang/p/7511060.html
Copyright © 2011-2022 走看看