删除链表重复元素(将重复的节点全部删除)

给出一个升序排序的链表,删除链表中的所有重复出现的元素,只保留原链表中只出现一次的元素。
例如:
给出的链表为1→2→3→3→4→4→5, 返回1→2→5.
给出的链表为1→1→1→2→3, 返回2→3.

/*
 * function ListNode(x){
 *   this.val = x;
 *   this.next = null;
 * }
 */

/**
  * 
  * @param head ListNode类 
  * @return ListNode类
  */
function deleteDuplicates( head ) {
    // write code here
    if(head == null || head.next == null){ return head}
    const top = {}
    top.next = head
    var current = top
    while(current.next && current.next.next){
        if(current.next.val == current.next.next.val){
            var val = current.next.val
            while(current.next && current.next.val == val){
                current.next = current.next.next
            }
        }else{
        current = current.next
        }
    }
    return top.next
}
module.exports = {
    deleteDuplicates : deleteDuplicates
};
链表算法 文章被收录于专栏

链表相关算法

全部评论

相关推荐

06-12 16:23
已编辑
小米_软件开发(准入职员工)
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务