class Solution:
def removeElements(self, head: Optional[ListNode], val: int) -> Optional[ListNode]:
dummy_head = ListNode(0,head)
a = dummy_head
while a.next:
if a.next.val == val:
a.next = a.next.next
else:a = a.next
return dummy_head.next
链表常用虚拟头节点,避免单独处理head的问题
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class MyLinkedList:
def __init__(self):
self.dummy_head = ListNode()
self.size = 0
def get(self, index: int) -> int:
if index<0 or index >= self.size:
return -1
a = self.dummy_head.next
for i in range(index):
a = a.next
return a.val
def addAtHead(self, val: int) -> None:
self.dummy_head.next = ListNode(val, self.dummy_head.next)
self.size += 1
def addAtTail(self, val: int) -> None:
a = self.dummy_head
while a.next:
a= a.next
a.next = ListNode(val,None)
self.size+=1
def addAtIndex(self, index: int, val: int) -> None:
if index > self.size or index<0: return
a = self.dummy_head
for i in range(index):
a =a.next
a.next = ListNode(val,a.next)
self.size += 1
def deleteAtIndex(self, index: int) -> None:
if index > self.size or index<0: return
a = self.dummy_head
for i in range(index):
a =a.next
a.next = a.next.next
self.size -= 1
虚拟头节点法
class Solution:
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
a = head
b = None
##None -> 1 -> 2 -> 3
b a
while a:
c= a.next
##None -> 1 -> 2 -> 3
b a c
a.next = b
##None <- 1 2 -> 3
b a c
b = a
##None <- 1 2 -> 3
b c
a = c
##None <- 1 2 -> 3
b a
return b
递归法
class Solution:
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
def reverse(cur,pre):
##递归的终止条件
if not cur : return pre
temp = cur.next
cur.next = pre
return reverse(temp,cur)
##注意调用reverse函数输入两个参数的顺序要一致
return reverse(head,None)