83. Remove Duplicates from Sorted List

Description

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.

Solution

Iteration

边遍历边移除重复的节点。

public class Solution {
    public ListNode deleteDuplicates(ListNode head) {
        ListNode curr = head;
        
        while (curr != null) {
            if (curr.next == null) break;
            
            if (curr.next.val == curr.val) {
                curr.next = curr.next.next; // remove the duplicate node
            } else {
                curr = curr.next;   // remain the node
            }
        }
        
        return head;
    }
}

你可能感兴趣的:(83. Remove Duplicates from Sorted List)