Remove Duplicates from Sorted List II (M)
题目
Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
Example 1:
Input: 1->2->3->3->4->4->5
Output: 1->2->5
Example 2:
Input: 1->1->1->2->3
Output: 2->3
题意
将有序链表中所有值重复的结点删除,只保留值不重复的结点。
思路
遍历链表,找到所有值不重复的结点,将其单独取出来依次加入到新链表中。
代码实现
Java
class Solution {
public ListNode deleteDuplicates(ListNode head) {
ListNode ans = null, last = null;
while (head != null) {
ListNode temp = head.next;
int count = 0;
// 判断head的值是否重复,并找到下一个值不同的结点
while (temp != null && temp.val == head.val) {
temp = temp.next;
count++;
}
if (count == 0) {
head.next = null; // 将该结点单独取出,断开与之后结点的联系
if (ans == null) {
ans = head;
last = head;
} else {
last.next = head;
last = last.next;
}
}
head = temp;
}
return ans;
}
}
JavaScript
/**
* @param {ListNode} head
* @return {ListNode}
*/
var deleteDuplicates = function (head) {
const dummy = new ListNode()
let p = dummy
while (head) {
if (head.next && head.next.val === head.val) {
const val = head.val
while (head && head.val === val) {
head = head.next
}
} else {
p.next = head
p = head
head = head.next
p.next = null
}
}
return dummy.next
}