删除给出链表中的重复元素(链表中元素从小到大有序),使链表中的所有元素都只出现一次
例如:
给出的链表为1→1→21to1to21→1→2,返回1→21 to 21→2.
给出的链表为1→1→2→3→31to1to 2 to 3 to 31→1→2→3→3,返回1→2→31to 2 to 31→2→3.
数据范围:链表长度满足 0≤n≤1000 le n le 1000≤n≤100,链表中任意节点的值满足 ∣val∣≤100|val| le 100∣val∣≤100
进阶:空间复杂度 O(1)O(1)O(1),时间复杂度 O(n)O(n)O(n)
示例:
输入:{1,1,2}
返回值:{1,2}
二、解决思路分两种情况:
当链表为空时,直接返回整个链表;当链表不为空时,使用cur指向头节点:
若cur.next为空时,返回链表;若不为空时,判断cur的值是否与cur.next相同,如果相同,则令cur.next=cur.next.next,若不相同,cur=cur.next,指针后移。
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def deleteDuplicates(self , head: ListNode) -> ListNode:
if not head:
return head
cur=head
while cur.next:
if cur.val==cur.next.val:
cur.next=cur.next.next
else:
cur=cur.next
return head



