Monday, September 16, 2013

Remove Duplicates from Sorted List

Q:
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.
A:
 ------------------------------------------3 rd Pass ---------------------------


public class Solution {
    public ListNode deleteDuplicates(ListNode head) {
        ListNode tail = head;
        while (tail != null && tail.next != null) {
            if (tail.val == tail.next.val) {
                tail.next = tail.next.next; // delete next node
            } else {
                tail = tail.next;
            }
        }
        return head;
    }
}
错误:  刚开始,while内部,又用了个while,写成了
while (tail != null && tail.next != null) {
            while (tail.val == tail.next.val) {......delete the next node........}
可是这样的话,就会导致 tail.next已经指向了null指针。 

--------------------------------------------第二遍------------------
public class Solution {
    public ListNode deleteDuplicates(ListNode head) {
        ListNode runner = head, nextRunner;
        while(runner!=null){
            if(runner.next == null)
                break;
             nextRunner = runner.next;
             if( nextRunner.val == runner.val){
                 runner.next = nextRunner.next;
             }else{
                 runner = nextRunner;
             }
        }
        return head;
    }
}


--------------------------------1st Pass -------------------------------------


就是两个指针,看是否相同。

public class Solution {
    public ListNode deleteDuplicates(ListNode head) {
        ListNode p1, p2; // p1 is the current node, p2 is his next neighbor
        if(head ==null || head.next == null){
            return head;
        }
        //now we have at least 2 Nodes in the list
        p1=head;
        p2 = head.next;
        while(p2!= null){
            if(p2.val == p1.val){
                // delete p2, 
                p1.next = p2.next;
                p2 = p1.next;
            }else{
                p1= p2;
                p2 = p1.next;
            }
        }
        return head;
    }
}

No comments:

Post a Comment