注意:首先要创建一个节点类!
在初始化链表的函数中记得设置链表长度,并且在对链表进行插入、删除时要更新链表长度。
class ListNode(object):
def __init__(self, val=0, next=None):
self.val=val
self.next=next
class MyLinkedList(object):
def __init__(self):
self.head=ListNode()
self.length=0
def get(self, index):
"""
:type index: int
:rtype: int
"""
if index>=self.length or index<0:
return -1
current=self.head.next
for i in range(index):
current=current.next
return current.val
def addAtHead(self, val):
"""
:type val: int
:rtype: None
"""
node=ListNode(val,self.head.next)
self.head.next=node
self.length+=1
def addAtTail(self, val):
"""
:type val: int
:rtype: None
"""
node=ListNode(val)
current=self.head
while current.next:
current=current.next
current.next=node
self.length+=1
def addAtIndex(self, index, val):
"""
:type index: int
:type val: int
:rtype: None
"""
if index>self.length or index<0:
return
# if index==self.length:
# self.addAtTail(val)
# return
# if index==0:
# self.addAtHead(val)
# return
current=self.head
for i in range(index):
current=current.next
node=ListNode(val,current.next)
current.next=node
self.length+=1
def deleteAtIndex(self, index):
"""
:type index: int
:rtype: None
"""
if index<0 or index>=self.length:
return
current=self.head
for i in range(index):
current=current.next
current.next=current.next.next
self.length-=1