题干
存在一个按升序排列的链表,给你这个链表的头节点 head
,请你删除所有重复的元素,使每个元素 只出现一次 。
返回同样按升序排列的结果链表。
示例 1:
输入:head = [1,1,2]
输出:[1,2]
解法
我们需要三个指针,分别是当前指针,前一个指针和后一个指针。
在循环时判断如果当前指针的值等于下一个指针的值那么我们就分三种情况:
- 第一种时起始时我们没有前一个prev元素,那么我们将head节点指向当前的next节点剩下的以此类推
- 第二种情况就是在我们有prev元素时,我们就要将prev元素指向next节点剩下的以此类推
- 第三种情况就是在结尾时我们的next节点没有值,我们直接将prev指向空然后next然后return即可
执行用时:72 ms, 在所有 JavaScript 提交中击败了100.00%的用户
内存消耗:39.7 MB, 在所有 JavaScript 提交中击败了64.80%的用户
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
var deleteDuplicates = function (head) {
// 双指针
if (head == null) {
return null
}
let pre = null;
let current = head;
let next = head.next;
while (current != null && next != null) {
if (current.val == next.val) {
if (pre == null) {
head = next;
current = head;
next = current.next
} else {
pre.next = next
if (next.next == null) {
return head
} else {
current = next
next = next.next
}
}
} else {
pre = current;
current = current.next;
next = next.next
}
}
return head
};