美文网首页
82. 删除排序链表中的重复元素 II

82. 删除排序链表中的重复元素 II

作者: one_zheng | 来源:发表于2018-10-16 23:16 被阅读5次

给定一个排序链表,删除所有含有重复数字的节点,只保留原始链表中 没有重复出现 的数字。

示例 1:

输入: 1->2->3->3->4->4->5
输出: 1->2->5
示例 2:

输入: 1->1->1->2->3
输出: 2->3

/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */
func deleteDuplicates(head *ListNode) *ListNode {
    if head == nil {
        return head
    }

    appear := make(map[int]int, 0)

    before := head
    current := head
    for {
        if current == nil {
            break
        }
        if appear[current.Val] >= 1 {
            appear[current.Val]++
            next := current.Next
            before.Next = next
            current = next
        } else {
            appear[current.Val]++
            before = current
            current = current.Next
        }
    }

    before = head
    current = head
    for {
        if current == nil {
            break
        }
        if appear[current.Val] > 1 {
            next := current.Next
            before.Next = next
            current = next
        } else {
            before = current
            current = current.Next
        }
    }

    if appear[head.Val] > 1 {
        return head.Next
    }

    return head
}

相关文章

网友评论

      本文标题:82. 删除排序链表中的重复元素 II

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