83. Remove Duplicates from Sorted List

Leetcode Linked List

Given a sorted linked list, delete all duplicates such that each element appear only once.

Example 1:

Input: 1->1->2
Output: 1->2
Example 2:

Input: 1->1->2->3->3
Output: 1->2->3
/**
 * Given a sorted linked list, delete all duplicates such that each element appear only once.
 * https://leetcode.com/problems/remove-duplicates-from-sorted-list/description/
 *
 * 由于链表是排序过的,那么直接比较相邻元素就可以发现重复的元素了,然后删除后面的重复元素。
 * NOTE: the Linked list is SORTED! Just compare adjacnet node to find repeat values.
 */
public class Q83RemoveDuplicatesFromSortedList {
    public ListNode deleteDuplicates(ListNode head) {
        if ((head == null) || (head.next==null)) {
            return head;
        }
        ListNode pos = head;
        while (pos.next != null) {
            // comparing adjacnet listnodes
            if (pos.next.val == pos.val) {
                pos.next = pos.next.next;
            } else {
                pos = pos.next;
            }
        }
        return head;
    }

    public static void main(String[] args) {
        int[] a = new int[]{1,1,1};
        //int[] a = new int[]{1,1,2,3,3};
        LinkedList list = new LinkedList(a);
        list.print();
        Q83RemoveDuplicatesFromSortedList q83 = new Q83RemoveDuplicatesFromSortedList();
        q83.deleteDuplicates(list.head);
        list.print();
    }
}