class Node:
def __init__(self, val):
self.val = val
self.next = None
class MyLinkedList:
def __init__(self):
self._head = Node(0) # 虚拟头部节点
self._count = 0 # 添加的节点数
def get(self, index: int) -> int:
"""
取第index的value,如果没有,返回-1
"""
if 0 <= index < self._count:
node = self._head
for _ in range(index + 1):
node = node.next
return node.val
else:
return -1
def addAtHead(self, val: int) -> None:
"""
在整个链表的头部增加节点
"""
self.addAtIndex(0, val)
def addAtTail(self, val: int) -> None:
"""
在链表的尾部增加节点
"""
self.addAtIndex(self._count, val)
def addAtIndex(self, index: int, val: int) -> None:
"""
在整个链表的任意地方增加节点
"""
if index < 0:
index = 0
elif index > self._count:
return
# 计数累加
self._count += 1
add_node = Node(val)
prev_node, current_node = None, self._head
for _ in range(index + 1):
prev_node, current_node = current_node, current_node.next
else:
prev_node.next, add_node.next = add_node, current_node
def deleteAtIndex(self, index: int) -> None:
"""
删除第index个节点
"""
if 0 <= index < self._count:
# 计数-1
self._count -= 1
prev_node, current_node = None, self._head
for _ in range(index + 1):
prev_node, current_node = current_node, current_node.next
else:
prev_node.next, current_node.next = current_node.next, None
# 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)
力扣刷题707、设计链表
最新推荐文章于 2024-11-09 05:20:46 发布