跳至主要內容

83. Remove Duplicates from Sorted List


83. Remove Duplicates from Sorted Listopen in new window

🟢   🔖  链表  🔗 LeetCodeopen in new window

题目

Given the head of a sorted linked list, delete all duplicates such that each element appears only once. Return the linked list sorted as well.

Example 1:

Input: head = [1,1,2]

Output: [1,2]

Example 2:

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

Output: [1,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.

题目大意

删除链表中重复的结点,以保障每个结点只出现一次。

解题思路

按照题意做即可。

代码

/**
 * @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;
			}
		} else {
			prev = prev.next;
		}
	}
	return res.next;
};

相关题目

相关题目
- [82. 删除排序链表中的重复元素 II](./0082.md)
- [🔒 Remove Duplicates From an Unsorted Linked List](https://leetcode.com/problems/remove-duplicates-from-an-unsorted-linked-list)