leetcode刷题笔记八十二题 删除排序链表中的重复元素 II

leetcode刷题笔记八十二题 删除排序链表中的重复元素 II

源地址:82. 删除排序链表中的重复元素 II

问题描述:

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

示例 1:

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

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

/**
 * Definition for singly-linked list.
 * class ListNode(var _x: Int = 0) {
 *   var next: ListNode = null
 *   var x: Int = _x
 * }
 */
object Solution {
    def deleteDuplicates(head: ListNode): ListNode = {
        //防止1,1,1,2,3这种head结点为需去除结点情况
        //设置新的头结点
        var cur = new ListNode(0)
        cur.next = head
        val start = cur
        while(cur != null && cur.next != null){
            var son = cur.next
            //如果相邻结果指相等,son指针指向后一个节点
            //即越过需去除结点
            while(son != null && cur.next.x == son.x) son = son.next
            //cur为上一个未被去除的结点
            //cur.next为本次可插入的首个结点
            //son此时为cur.next后第一个与其值不相等的结点
            //出现1,2,3 中 son == cur.next.next情况
            //cur指针后移
            //否则跳过以cur.next为首的重复结点
            if(son == cur.next.next) cur = cur.next
            else cur.next = son
        }
        return start.next
    }
}

猜你喜欢

转载自www.cnblogs.com/ganshuoos/p/13375605.html
今日推荐