虚拟节点dummyhead:
dummy_head = ListNode(next = head)
cur = dummy_head#想要移除节点,需要知道前一个节点!
class Solution:
def removeElements(self, head: Optional[ListNode], val: int) -> Optional[ListNode]:
dummy_head = ListNode(next = head)
cur = dummy_head
while cur.next:
if cur.next.val == val:
cur.next = cur.next.next
else:
cur = cur.next
return dummy_head.next
class Node(object):#
def __init__(self, x=0):
self.val = x
self.next = None
class MyLinkedList:
def __init__(self):#初始化
self.head = Node()
self._count = 0
def get(self, index: int) -> int:
if index < 0 or index >= self._count:
return -1
cur = self.head.next
while index:
cur = cur.next
index -= 1
return cur.val
def addAtHead(self, val: int) -> None:
if self._count==0:
self.head.next = Node(val)
else:
node = Node(val)
node.next = self.head.next
self.head.next = node
self._count += 1
def addAtTail(self, val: int) -> None:
cur = self.head
node = Node(val)
while cur.next:#找到最后一个节点
cur = cur.next
cur.next = node
self._count += 1
def addAtIndex(self, index: int, val: int) -> None:
if index < 0:
self.addAtHead(val)
return
elif index == self._count:
self.addAtTail(val)
return
elif index > self._count:
return
node = Node(val)
cur = self.head#需要前驱节点,所以这里cur指向的是虚拟头节点
while(index):
cur = cur.next
index -= 1
node.next = cur.next
cur.next = node
self._count += 1
def deleteAtIndex(self, index: int) -> None:
if index < 0 or index >= self._count:
return
cur = self.head
while(index):
cur = cur.next
index -= 1
cur.next = cur.next.next
self._count -= 1
确定 pre,cur,cur.next
比如1-->2想要实现原地反转。
实现none-->1的反转,变成1-->none
因此初始化时,pre=none。cur = head(此时指向1)。
首先需要用tmp记录下一个cur,也就是2,不然1-->2这个链接断了就找不到2了。
实现cur-->pre;
此时的cur就是下一个的pre,因此pre指向cur。此时pre=1
cur指向刚刚记录的下一个cur,此时cur=2
class Solution:
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
pre = None
cur = head
while cur:
temp = cur.next
cur.next = pre
pre = cur
cur = temp
return pre