0722更新
伪头指针
# 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 == None:
return None
faker = ListNode('skt')
faker.next = head
cur = faker
last_val = head.val
while cur.next != None:
if cur.val != cur.next.val:
cur = cur.next
else:
cur.next = cur.next.next
return faker.next
思路是设置两个指针
其中,一个this指向上一个首次出现的数字(初始化为None)
另一个cur指向当前考察的数字
一开始,this为None,cur从第一个元素开始,
当this为None时,我们令this指向cur所指的元素
此后,若cur所指元素值等于this所指元素值,我们让this的next指cur的next
若不等时,我们先更新this的next为cur,再更新this为cur
# 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:
this = None#存放上一个要保留的元素
cur = head
while cur != None:
if this == None:
this = cur
else:#有
if cur.val != this.val:
this.next = cur
this = cur
elif cur.val == this.val:
this.next = cur.next
cur = cur.next
return head