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;
        }
    }
  • 相关阅读:
    poj 3669 Meteor Shower
    poj 3232 Accelerator
    poj 2155 Matrix
    poj 3628 Bookshelf 2
    cf C. Maze
    cf B. Fox Dividing Cheese
    hdu Children’s Queue
    cf D. Broken Monitor
    cf C. Mittens
    cf B. Berland Bingo
  • 原文地址:https://www.cnblogs.com/RazerLu/p/3540021.html
Copyright © 2011-2022 走看看