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

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

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

问题描述:

给定一个排序链表,删除所有重复的元素,使得每个元素只出现一次。

示例 1:

输入: 1->1->2
输出: 1->2
示例 2:

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

/**
 * Definition for singly-linked list.
 * class ListNode(var _x: Int = 0) {
 *   var next: ListNode = null
 *   var x: Int = _x
 * }
 */
/**
本题较为简单,与82题解法基本一致
通过son获取与cur值不同的首个结点
将cur指向son即可
*/
object Solution {
    def deleteDuplicates(head: ListNode): ListNode = {
        var cur = head
        while(cur != null && cur.next != null){
            var son = cur.next
            while(son != null && cur.x == son.x) son = son.next
            cur.next = son
            cur = cur.next
        }
        return head
    }
}

猜你喜欢

转载自www.cnblogs.com/ganshuoos/p/13375610.html