Sunday, June 1, 2014

Remove Duplicates from Sorted List

This problem is quite easy. Use a current node and a node just before it to traverse this linked list, compare the value of current node with preNode, if same, delete current node, otherwise, move both to next one.

/**
 * 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) {
        if (head == null || head.next == null) return head;
     
        ListNode preNode = head;
        int value = preNode.val;
        ListNode currentNode = head.next;
        while(currentNode !=null ){
         
            if(value == currentNode.val){
                preNode.next = currentNode.next;
                currentNode.next = null;
                currentNode = preNode.next;
            }
         
            else{
                preNode = preNode.next;
                currentNode = currentNode.next;
                value = preNode.val;
            }
        }
        return head;
    }
}

No comments:

Post a Comment