链表类的题目要注意不要让自己的链表丢失了,所有就有了虚拟头节点;先链接后断开这些基本的操作
python一些数据结构的定义需要好好注意下
class ListNode: # 链表
def __init__(self,val):
self.val = val
self.next = None
class binTree: # 二叉树
def __init__(self, val):
self.val = val
self.left = None
self.right = None
203. 移除链表元素
class Solution:
def removeElements(self, head: Optional[ListNode], val: int) -> Optional[ListNode]:
preHead = ListNode(0)
preHead.next = head
cur = preHead
if cur.next == None: # 空链表
return head
while (cur != None and cur.next != None): # 终止的条件
while cur.next != None and cur.next.val == val: # 连续有相等 74.56
cur.next = cur.next.next
# if cur.next.val == val: # 58.5 # 感觉像是因为跳转地址的原因?
# cur.next = cur.next.next
# continue
cur = cur.next
return preHead.next
707. 设计链表
class ListNode:
def __init__(self, val):
self.val = val
self.next = None
class MyLinkedList:
def __init__(self):
self.size = 0
self.predHead = ListNode(0)
def get(self, index: int) -> int:
if index < 0 or index >= self.size:
return -1
cur = self.predHead.next
for _ in range(index):
cur = cur.next
return cur.val
def addAtHead(self, val: int) -> None:
self.addAtIndex(0, val)
def addAtTail(self, val: int) -> None:
self.addAtIndex(self.size, val)
def addAtIndex(self, index: int, val: int) -> None:
if index < 0 or index > self.size:
return None
self.size += 1
addListNode = ListNode(val)
cur = self.predHead
for _ in range(index):
cur = cur.next
addListNode.next = cur.next
cur.next = addListNode
def deleteAtIndex(self, index: int) -> None:
if index < 0 or index >= self.size:
return None
self.size -= 1
cur = self.predHead
for _ in range(index):
cur = cur.next
cur.next = cur.next.next
# Your MyLinkedList object will be instantiated and called as such:
# obj = MyLinkedList()
# param_1 = obj.get(index)
# obj.addAtHead(val)
# obj.addAtTail(val)
# obj.addAtIndex(index,val)
# obj.deleteAtIndex(index)
206. 反转链表
class Solution:
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
preHead = ListNode(0)
if head is None:
return head
headNext = head.next
while headNext != None and head != None:
head.next = preHead.next # 接上新的链表
preHead.next = head # 虚拟头节点更换位置
head = headNext # 且回到老链表
headNext = headNext.next #
# 最后一个节点
head.next = preHead.next # 接上新的链表
preHead.next = head # 虚拟头节点更换位置
head = headNext # 且回到老链表
return preHead.next