83. Remove Duplicates from Sorted List

132 阅读1分钟

题目描述

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

解题思路

这是一个简单的链表题目, 设置临时指针, 如果指针的val等于下一个的值, 就跳过, 不相等就重新赋值并且后移
时间复杂度: O(n)

示例代码

func deleteDuplicates(_ head: ListNode?) -> ListNode? {

    guard var result = head  else {
        return head
    }
    var temp = result.next
    while temp != nil {
        if temp!.val == result.val {
            temp = temp!.next
        }else {
            result.next = temp
            result = temp!
            temp = temp!.next
        }
    }
    result.next = nil
    return head
}