跳至主要內容

82. 删除排序链表中的重复元素 II


82. 删除排序链表中的重复元素 II

🟠   🔖  链表 双指针  🔗 力扣open in new window LeetCodeopen in new window

题目

Given the head of a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list. Return the linked list sorted as well.

Example 1:

Input: head = [1,2,3,3,4,4,5]

Output: [1,2,5]

Example 2:

Input: head = [1,1,1,2,3]

Output: [2,3]

Constraints:

  • The number of nodes in the list is in the range [0, 300].
  • -100 <= Node.val <= 100
  • The list is guaranteed to be sorted in ascending order.

题目大意

给定一个已排序的链表的头 head , 删除原始链表中所有重复数字的节点,只留下不同的数字 。返回 已排序的链表

解题思路

按照题意做即可。

代码

/**
 * @param {ListNode} head
 * @return {ListNode}
 */
var deleteDuplicates = function (head) {
	let res = new ListNode(0, head);
	let prev = res;

	while (prev.next && prev.next.next) {
		if (prev.next.val === prev.next.next.val) {
			// 删除与 prev.next 重复的节点
			while (
				prev.next &&
				prev.next.next &&
				prev.next.val === prev.next.next.val
			) {
				prev.next = prev.next.next;
			}
			// 删除 prev.next 节点
			prev.next = prev.next.next;
		} else {
			prev = prev.next;
		}
	}
	return res.next;
};

相关题目

题号标题题解标签难度力扣
83删除排序链表中的重复元素[✓]链表🟢🀄️open in new window 🔗open in new window
1836从未排序的链表中移除重复元素 🔒哈希表 链表🟠🀄️open in new window 🔗open in new window