Question

Formatted question description: https://leetcode.ca/all/83.html

 83	Remove Duplicates from Sorted 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

 @tag-linkedlist

Algorithm

Traverse this linked list, and compare each node with the following nodes. If the value of the node is the same, just skip the next pointer of the previous node with the same value and point to the next node. After traversing in this way, all duplicate nodes will be skipped, and the linked list left will have no duplicates.

Code

Java

public class Remove_Duplicates_from_Sorted_List {
    /**
     * 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 dummy = new ListNode(0);
            // dummy.next = head;

            ListNode prev = head;
            ListNode p = head.next;

            while (p != null) {
                if (p.val == prev.val) {
                    prev.next = p.next;
                    p = p.next;
                } else {
                    prev = p;
                    p = p.next;
                }

            }

            return head;
        }
    }
}

All Problems

All Solutions