class ListNode(object):
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class MyLinkedList:
def __init__(self):
self.root = ListNode()
self.size = 0
def get(self, index):
if 0 <= index < self.size:
cur = self.root.next
while index:
cur = cur.next
index -= 1
return cur.val
else:
return -1
def addAtHead(self, val):
node = ListNode(val)
node.next = self.root.next
self.root.next = node
self.size += 1
def addAtTail(self, val):
node = ListNode(val)
cur = self.root
while cur.next:
cur = cur.next
cur.next = node
self.size += 1
def addAtIndex(self, index, val):
if index < 0 or index > self.size:
return
cur = self.root
for i in range(index):
cur = cur.next
cur.next = ListNode(val, cur.next)
self.size += 1
def deleteAtIndex(self, index):
if index < 0 or index >= self.size:
return
cur = self.root
for i in range(index):
cur = cur.next
cur.next = cur.next.next
self.size -= 1
linklist = MyLinkedList()
linklist.addAtHead(1)
linklist.addAtTail(3)
linklist.addAtIndex(1, 2)
linklist.deleteAtIndex(1)
print(linklist.get(1))
while linklist.root:
print(linklist.root.val)
linklist.root = linklist.root.next
707. 设计链表
最新推荐文章于 2024-10-30 13:16:11 发布