Given a sorted linked list, delete all duplicates such that each element appear only once.
For example, Given 1->1->2, return 1->2. Given 1->1->2->3->3, return 1->2->3.
链表删除操作的应用,即 cur.next = cur.next.next,时间复杂度为 O(n)。
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def deleteDuplicates(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
cur = head
if cur == None or cur.next == None: # 如果是空链表或链表只有一个元素
return head
while cur.next != None:
if cur.val == cur.next.val: # 如果连续两个值相等,则删除后一个
cur.next = cur.next.next
else: # 如果不相等,当前指针后移
cur = cur.next
return head