美文网首页
83. Remove Duplicates from Sorte

83. Remove Duplicates from Sorte

作者: 强布斯 | 来源:发表于2019-01-06 22:34 被阅读0次

    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

    分析:看到题设我开始以为是数组去重问题,先想到的是设置两个指针并移动的思路。仔细一看是链表,考虑到链表删除节点还是比较容易的,只需要把next指针指向下一个节点即可,所以不需要设置两个指针。思路是设置一个指针a指向头结点,比较a和下一个节点b,如果相等就移除节点b;如果不等就把a指针指向b节点,继续向下遍历即可,代码如下

    func deleteDuplicates(_ head: ListNode?) -> ListNode? {
            
            guard let _ = head else {
                return nil;
            }
            
            var temp:ListNode = head!;
            
            while ((temp.next) != nil) {
                if temp.val != temp.next?.val {
                    temp = temp.next!;
                } else {
                    temp.next = temp.next?.next;
                }
            }
            
            return head;
    
        }
    

    相关文章

      网友评论

          本文标题:83. Remove Duplicates from Sorte

          本文链接:https://www.haomeiwen.com/subject/hgverqtx.html