给定一个排序链表,删除所有重复的元素,使得每个元素只出现一次。
示例 1:
输入: 1->1->2 输出: 1->2
示例 2:
输入: 1->1->2->3->3 输出: 1->2->3
思路:如果当前结点值==下一结点值,就把当前结点的next指向下下结点。
/** * Definition for singly-linked list. * public class ListNode { * public var val: Int * public var next: ListNode? * public init(_ val: Int) { * self.val = val * self.next = nil * } * } */ class Solution { func deleteDuplicates(_ head: ListNode?) -> ListNode? { var current = head while nil != current && nil != current?.next { if current?.val == current?.next?.val { current?.next = current?.next?.next }else{ current = current?.next } } return head } }