简体   繁体   中英

How to get node for negative index in a linked list?

Hi I'm a beginner in Python and I've just started learning linked list. I wrote a method get node that gets the node at a specific index in the list but now I wanna try getting nodes from negative index. For example, if a_list=[1,2,3] a_list[-1] will be equal to 3 and so on. This is my get_node method that only works for positive index:

def _get_node(self, index):
    if index >0 and index >=len(self) :
        raise IndexError( "Positive index out of range")
    node=self.head
    for _ in range(index):
        node=node.next
    return node

Now I try to write another method for negative index:

 def _get_nodeNegative(self, index):
    if index <0 and index < -1 *len(self) :
        raise IndexError( "Positive index out of range")
    if index==-1:
        node=self._get_node(len(self)-1)

    else:
        for _ in range(index, 0 ,1):
          //Problem here
            node=node.next
    return node

Problem is linked list can only iterate forward so if I try to get a_list[-2] I get the error AttributeError: 'NoneType' object has no attribute 'next'.

Any suggestions would be helpful.

You've written

node=node.next

but there is no "node" object defined hence it is a 'NoneType' object. The only time you define it is in the if statement above it but essentially if you go into the else statement you haven't created a node object to perform node.next.

The relationship between negative indices and positive indices are positive indices-len(self)=negative indices so all I have to change in getNodeNegative is

for _ in range(index, 0 ,1):
        node=self._get_node(index+len(self))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM