Reputation: 339
Just to start, this is homework, so I'm merely looking for a hint here. I'm pretty new to Python and programming in general. I'm supposed to implement a cursor-based list that is doubly linked. I'm having some trouble with inserting onto the list. My instructor provided a simple Node class a a Node2Way class. He also provided the init method:
from node import Node
class Node2Way(Node):
def __init__(self,initdata):
Node.__init__(self,initdata)
self.previous = None
def getPrevious(self):
return self.previous
def setPrevious(self,newprevious):
self.previous = newprevious
Here is what I have so far (just the pertinent methods):
from node2way import Node2Way
class CursorBasedList(object):
""" Linked implementation of a positional list."""
def __init__(self):
""" Creates an empty cursor-based list."""
self._header = Node2Way(None)
self._trailer = Node2Way(None)
self._trailer.setPrevious(self._header)
self._header.setNext(self._trailer)
self._current = None
self._size = 0
def insertAfter(self, item):
"""Inserts item after the current item, or
as the only item if the list is empty. The new item is the
current item."""
temp = Node2Way(item)
if self.isEmpty():
self._header.setNext(temp)
self._trailer.setPrevious(temp)
else:
temp.setNext(self._current.getNext())
self._current.setNext(temp)
temp.setPrevious(self._current)
self._current = temp
self._size+=1
When I test the insertAfter method out, it works for adding the first item, but when I try to add the second item, it says that self._current is None type and can't use the getNext method. I don't know if there is another way to get temp to reference the node after the current one. I'm not sure what I'm doing wrong, or even if anything I'm doing is right. I think once I get the insertAfter method right, I'll be fine with the insertBefore method.
Any hints would be appreciated. Thank you in advance! :)
Upvotes: 0
Views: 1490
Reputation: 24788
In the case of
if self.isEmpty():
self._header.setNext(temp)
self._trailer.setPrevious(temp)
You never set the previous and next nodes of temp
.
Upvotes: 1