LeetCode – 83. Remove Duplicates from Sorted List

題目連結: https://leetcode.com/problems/remove-duplicates-from-sorted-list/

Given the head of a sorted linked list, delete all duplicates such that each element appears only once. Return the linked list sorted as well.

// Test case:
// empty list
// 1 -> 2 -> 3
// 2 -> 2 
// 2 -> 2 -> 2
    func deleteDuplicates(_ head: ListNode?) -> ListNode? {
        var ptr = head
        while ptr != nil {
          if ptr?.val == ptr?.next?.val {
              ptr?.next = ptr?.next?.next
          } else {
              ptr = ptr?.next
          }
        }
        return head
    }

%d 位部落客按了讚: