思路:
利用虚拟头节点来过度索要插入或者删除的节点
'''定义一个新的Node来存储比较节点'''
class ListNode:
def __init__(self,val=0,next=0):
self.val=val
self.next=next
class MyLinkedList:
def __init__(self):
'''令dunmy_head=创建的新Node,并且规定大小为零'''
self.dunmy_head=ListNode()
self.size=0
'''获取第n个节点值,对进行插入的节点值比较大小,并且将当前定义的current变为dunmy_head的下一个新元素节点。
对当前插入的index值进行循环遍历,curremt=curremt.next将当前使用的current变到下一个next节点,最后返回当前current所在的节点值'''
def get(self, index: int) -> int:
if index<0 or index>=self.size:
return -1
current=self.dunmy_head.next
for i in range(index):
current=current.next
return current.val
'''添加头节点:
定义了虚拟头节点将dunmy_head.next为新Node,并且存储完全当前的listNode节点值和dunmy_head的下一个节点,此时将链表的长度增加1'''
def addAtHead(self, val: int) -> None:
self.dunmy_head.next=ListNode(val,self.dunmy_head.next)
self.size+=1
'''尾部添加链表节点current=dunmy_head方便后续使用,然后利用while循环对self.dunmy_head后续的单个链表进行遍历:
currrnt=current.next即为将当前使用的链表元素往后移一位。后续在添加current.next=ListNode(val)即添加NOde中存储的新节点,并且将链表长度增加1'''
def addAtTail(self, val: int) -> None:
current=self.dunmy_head
while current.next:
current=current.next
current.next=ListNode(val)
self.size+=1
'''插入节点:
先对当前插入的index进行判断,汝若满足index<0或者index的长度大于被插入的链表长度时,返回,不做处理。
最后对当前的current进行利用,对当前插入的链表进行遍历,将current被赋值给下一个节点,随后将当前插入的元素节点再次放入curent前即可'''
def addAtIndex(self, index: int, val: int) -> None:
if index<0 or index>self.size:
return
current=self.dunmy_head
for i in range(index):
current=current.next
current.next=ListNode(val,current.next)
self.size+=1
'''删除节点:
先判断当前index的值,最后进行循环遍历将当前的current.next直接等于current的下一个的下一个节点(current.next=current.next.next)
将链表的长度减1'''
def deleteAtIndex(self, index: int) -> None:
if index<0 or index>=self.size:
return
current=self.dunmy_head
for i in range(index):
current=current.next
current.next=current.next.next
self.size-=1
# 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)