1. 程式人生 > 實用技巧 >leetcode刷題筆記八十二題 刪除排序連結串列中的重複元素 II

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
    }
}