力扣(LeetCode)删除排序链表中的重复元素
1、题目:Given a sorted linked list, delete all duplicates such that each element appear only once.
Example 1:
Input: 1->1->2
Output: 1->2
Example 2:
Input: 1->1->2->3->3
Output: 1->2->3
2、代码:python
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def deleteDuplicates(self, head: ListNode) -> ListNode:
if head is None or head.next is None:
return head
cur = head
while cur.next is not None:
if cur.val != cur.next.val:
cur = cur.next
else:
cur.next = cur.next.next # 删除相同的元素
return head
3、复杂度分析
时间复杂度:O(n),我们遍历了包含有 n 个元素的链表一次。
空间复杂度:O(1),需要额外的常数级空间。