[leedcode 83] Remove Duplicates from Sorted List

2831 단어 remove
Given a sorted linked list, delete all duplicates such that each element appear only once.
For example,Given  1->1->2 , return  1->2 .Given  1->1->2->3->3 , return  1->2->3 .
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode deleteDuplicates(ListNode head) {
        ////        ,    index        ,first      ,pre first   ,           
        //          ,            ,    ,    ,          
        if(head==null||head.next==null) return head;
      /*  ListNode pre=head;
        ListNode first=head.next;
        ListNode index=head;
        while(first!=null){
            if(index.val==first.val){
                pre.next=first.next;
                first=first.next;
            }else{
                pre=first;
                first=first.next;
                index=index.next;
            }
        }
        return head;*/
        ListNode pre=head;
        while(pre.next!=null){
            if(pre.next.val==pre.val){
                pre.next=pre.next.next;
            }else{
                pre=pre.next;
            }
        }
        return head;
    }
}

좋은 웹페이지 즐겨찾기