83. Remove Duplicates from Sorted List

Total Accepted: 100371
Total Submissions: 278401
Difficulty: Easy

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.

Java:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
/**
 * 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) {
        if(head == null||head.next==null)
            return head;
        ListNode curr = head;
        ListNode itr = head;
        while(curr.next != null) {
            while(itr.val == curr.val && itr.next != null) {
                itr = itr.next;
            }
            if(curr.val != itr.val) {
                curr.next = itr;
                curr = curr.next;
            }
            else {
                curr.next = null;
            }
        }
        return head;
    }
}

打个小广告

欢迎加入我的小专栏「基你太美」一起学习。