class LinkedList:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class MyLinkedList:
def __init__(self, val=0, next=None):
self.head = LinkedList()
self.size = 0
def get(self, index: int) -> int:
if index < 0 or index >= self.size:
return -1
cur = self.head.next
for i in range(index):
cur = cur.next
return cur.val
def addAtHead(self, val: int) -> None:
self.head.next = LinkedList(val, self.head.next)
self.size += 1
def addAtTail(self, val: int) -> None:
cur = self.head
while cur.next:
cur = cur.next
cur.next = LinkedList(val)
self.size += 1
def addAtIndex(self, index: int, val: int) -> None:
if index < 0 or index > self.size:
return
cur = self.head
for i in range(index):
cur = cur.next
cur.next = LinkedList(val, cur.next)
self.size += 1
def deleteAtIndex(self, index: int) -> None:
if index < 0 or index >= self.size:
return
cur = self.head
for i in range(index):
cur = cur.next
cur.next = cur.next.next
self.size -= 1
主要合法输入判断中,对已有的节点判断加等号,没有不加
要长脑子了.jpg