20200626
编写代码,移除未排序链表中的重复节点。保留最开始出现的节点。
输入:[1, 2, 3, 3, 2, 1]
输出:[1, 2, 3]
输入:[1, 1, 1, 1, 2]
输出:[1, 2]
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
var removeDuplicateNodes = function(head) {
if (head == null) return head;
const map = new Map();
map.set(head.val, true);
let node = head.next;
let prev = head;
while (node) {
if (map.has(node.val)) {
prev.next = node.next;
} else {
map.set(node.val, true);
prev = prev.next;
}
node = node.next;
}
return head;
};
const removeDuplicateNodes = (head) => {
let ob = head;
while (ob != null) {
let oc = ob;
while (oc.next != null) {
if (oc.next.val == ob.val) {
oc.next = oc.next.next;
} else {
oc = oc.next;
}
}
ob = ob.next;
}
return head;
};
博客: 小书童博客(http://gaowenju.com)
公号: 坑人的小书童