美文网首页
js 删除链表中重复的节点

js 删除链表中重复的节点

作者: McDu | 来源:发表于2017-08-24 22:31 被阅读136次

leetcode 82. Remove Duplicates from Sorted List II

题目描述:
给定一个排序的链接列表,删除所有具有重复数字的节点,从原始列表中只留下不同的数字。
例如, 给定1-> 2-> 3-> 3-> 4-> 4-> 5,返回1-> 2-> 5。
给定1-> 1-> 1-> 2-> 3,返回2-> 3。


1. js 中如何操作链表:

JavaScript 版数据结构与算法(三)链表
可以看出JavaScript中的链表是通过不断 new 出来节点,并在节点的next属性上继续 new 创建出来的

function ListNode(val) {
     this.val = val;
     this.next = null;
 }
var head = new ListNode(10);
head.next = new ListNode(22);
console.log(head);

结构大概长这样:

{
  val: 10,
  next: {
    val: 22,
    next: null
  }
}

2. 具体实现:

/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */
/**
 * @param {ListNode} head
 * @return {ListNode}
 */
var deleteDuplicates = function(head) {
    var dummy = new ListNode(-1);   // 创建一个虚拟节点
    
    dummy.next = head;                     //让虚拟节点位于头节点之前
    var pre = head = dummy;             
    
    while(pre){                          // pre !== null
        var cur = pre.next;
        var isDup = false;
        
        while(cur && cur.next && cur.val === cur.next.val){
            isDup = true;
            var next = cur.next;              // 这时,准备删除 cur.next 节点
            cur.next = next.next;           // 让 cur.next 指向 cur.next.next
            next.next = null;                  // cur.next 这个节点的指向为 null
        }
        
        if(isDup){                // 这里,准备删除 cur 节点,因为重复的全部要删除
            pre.next = cur.next;     // pre.next 指向 cur.next; 
            cur.next = null;           // cur.next 这个节点的值设为 null,cur 前面没人指着,后面指向 null,即被删除了
            continue;
        }
        
        pre = cur;
    }
    return dummy.next;
};

参考资料:
https://github.com/chihungyu1116/leetcode-javascript

相关文章

网友评论

      本文标题:js 删除链表中重复的节点

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