class ListNode:
def __init__(self,x:int):
self.val = x
self.next = None #链表节点数据结构
class MyLinkedList:
def __init__(self): #哨兵节点, i.e.伪头节点数据结构 其后可增删改查链表节点
self.size = 0
self.head = ListNode(0)
def get(self,index:int) -> int:
if 0<= index < self.size:
cur = self.head
for _ in range(index+1): #依次找到待取节点
cur = cur.next
return cur.val
else:
return -1
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 > self.size:
return
elif index < 0:
index = 0
self.size += 1
add_node = ListNode(val)
cur = self.head
for _ in range(index): #依次找到待插入位置先驱节点
cur = cur.next
add_node.next = cur.next
cur.next = add_node
def deleteAtIndex(self,index:int) -> None:
if index<0 or index >= self.size:
return
self.size -= 1
cur = self.head
for _ in range(index): #依次找到待插入位置先驱节点
cur = cur.next
cur.next = cur.next.next
Leetcode 707. 设计链表 Design Linked List - Python 单链表法
于 2022-02-24 10:49:40 首次发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)