classListNode:def__init__(self,x):self.val=xself.next=Noneself.prev=NoneclassMyLinkedList(object):def__init__(self):"""Initialize your data structure here."""self.size=0self.head,self.tail=ListNode(0),ListNode(0)self.head.next=self.tail # 這兩句的作用是什么,變成一個環?self.tail.prev=self.headdefget(self, index):"""Get the value of the index-th node in the linked list. If the index is invalid, return -1.:type index: int:rtype: int"""if index<0or index>=self.size:return-1if index+1<self.size-index:curr=self.headfor _ inrange(index+1):# [0,index]curr=curr.nextelse:curr=self.tailfor _ inrange(self.size-index):curr=curr.prevreturn curr.valdefaddAtHead(self, val):"""Add a node of value val before the first element of the linked list. After the insertion, the new node will be the first node of the linked list.:type val: int:rtype: None"""pred,succ=self.head,self.head.nextself.size+=1to_add=ListNode(val)to_add.prev=predto_add.next=succpred.next=to_addsucc.prev=to_adddefaddAtTail(self, val):"""Append a node of value val to the last element of the linked list.:type val: int:rtype: None"""succ,pred=self.tail,self.tail.prevself.size+=1to_add=ListNode(val)to_add.prev=predto_add.next=succpred.next=to_addsucc.prev=to_adddefaddAtIndex(self, index, val):"""Add a node of value val before the index-th node in the linked list. If index equals to the length of linked list, the node will be appended to the end of linked list. If index is greater than the length, the node will not be inserted.:type index: int:type val: int:rtype: None"""if index>self.size:returnif index<0:index=0if index<self.size-index:pred=self.headfor _ inrange(index):pred=pred.nextsucc=pred.nextelse:succ=self.tailfor _ inrange(self.size-index):succ=succ.prev#print(succ.val)pred=succ.prevself.size+=1to_add=ListNode(val)#print(pred.val,succ.val,to_add.val)to_add.prev=predto_add.next=succpred.next=to_addsucc.prev=to_adddefdeleteAtIndex(self, index):"""Delete the index-th node in the linked list, if the index is valid.:type index: int:rtype: None"""if index<0or index>=self.size:returnif index<self.size-index:pred=self.headfor _ inrange(index):pred=pred.nextsucc=pred.next.nextelse:succ=self.tailfor _ inrange(self.size-index-1):succ=succ.prevpred=succ.prev.prevself.size-=1pred.next=succsucc.prev=pred