zoukankan      html  css  js  c++  java
  • Remove Duplicates from Sorted List II

    Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.

    For example,
    Given 1->2->3->3->4->4->5, return 1->2->5.
    Given 1->1->1->2->3, return 2->3.

    解题思路 :

      建立 fake noed 加在head 前面。cur = head; 比较cur 和  cur.next的值, 如果相等,记录下该值,并且从pre.next开始遍历到不等于 val的那个值,将中间的node 删除。

      

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) {
     *         val = x;
     *         next = null;
     *     }
     * }
     */
    public class Solution {
        public ListNode deleteDuplicates(ListNode head) {
            ListNode safe=new ListNode(0);
            safe.next=head;
            // 记录重复节点的值
            int val=0;
            ListNode pre=safe;ListNode cur=head;
            while(cur!=null&&cur.next!=null){
                ListNode n = cur.next;
                if(n.val == cur.val){
                    val=cur.val;
                    // 从pre.next 开始遍历,如果pre.next 不为null 且值等于val,删除该节点 
                    while(pre.next!=null&&pre.next.val==val){
                        pre.next=pre.next.next;
                    }
                    cur=pre.next;
                }else{
                    pre=cur;
                    cur=cur.next;
                }
                
            }
            return safe.next;
        }
    }
  • 相关阅读:
    #include <functional>
    3.3内联函数
    如何查看内存占用和运行速度
    属性和方法的动态绑定和限制
    __slots__节约空间
    函数进阶之一等对象
    python继承之super
    python的方法VSjava方法
    python面向对象基础(三)内置方法 __xx__
    python面向对象基础(二)反射
  • 原文地址:https://www.cnblogs.com/RazerLu/p/3540021.html
Copyright © 2011-2022 走看看