[leedcode 82] Remove Duplicates from Sorted List II

3851 단어 remove
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 .
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    //        ,     :
    //1:         p,               
    //s           ,    t  t        s,    ,     ,    s.next==t  ,       ,
    //       ,    p  t,        ,    s   
    //      s           ,  s         , t      ,  s t      , s   ,  p.next=null
    public ListNode deleteDuplicates(ListNode head) {
        if(head==null||head.next==null) return head;
        ListNode newHead=new ListNode(-1);
        newHead.next=head;
        ListNode p=newHead;
        ListNode s=head;
        ListNode t=head.next;
        while(t!=null){
            if(t.val==s.val){
                t=t.next;
            }else{
                if(s.next==t){
                    //p.next=s;
                    p=s;
                    s=t;
                    t=t.next;
                }else{
                    p.next=t;
                    s=t;
                    t=t.next;
                    
                }
            }
           
        }
        if(s.next!=null){
            p.next=null;
        }
        return newHead.next;
    }
}

좋은 웹페이지 즐겨찾기