83.remove-duplicates-from-sorted-list
Statement
Metadata
- Link: 删除排序链表中的重复元素
- Difficulty: Easy
- Tag:
链表
给定一个已排序的链表的头 head
, 删除所有重复的元素,使每个元素只出现一次 。返回 已排序的链表 。
示例 1:
![](problem-assets/https:--assets.leetcode.com-uploads-2021-01-04-list1.jpg)
输入:head = [1,1,2]
输出:[1,2]
示例 2:
![](problem-assets/https:--assets.leetcode.com-uploads-2021-01-04-list2.jpg)
输入:head = [1,1,2,3,3]
输出:[1,2,3]
提示:
- 链表中节点数目在范围
[0, 300]
内 -100 <= Node.val <= 100
- 题目数据保证链表已经按升序 排列
Metadata
- Link: Remove Duplicates from Sorted List
- Difficulty: Easy
- Tag:
Linked List
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:
![](problem-assets/https:--assets.leetcode.com-uploads-2021-01-04-list1.jpg)
Input: head = [1,1,2]
Output: [1,2]
Example 2:
![](problem-assets/https:--assets.leetcode.com-uploads-2021-01-04-list2.jpg)
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.
Solution
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def deleteDuplicates(self, head: ListNode) -> ListNode:
rt = head
res = rt
while head:
if rt.val != head.val:
rt.next = head
rt = rt.next
head = head.next
rt.next = None
return res
最后更新: October 11, 2023