A singly linked list with two classes, Node and LinkedList, is easy enough to implement. however my issue is when it comes to a singly linked list with only first node access (No stored length, No last node access, and without the use of dummy nodes). The special methods I can't wrap my head around or find much about online are similar to pythons built-in list operations with O(1) complexity, such as follows:
aa = LinkedList() -- creates empty list
aa.first() -- similar to aa[0]
aa.rest() -- similar to aa[1:]
aa.cons(item) -- similar to aa[item:]
[item] + aa -- similar to aa.insert(0, item)
Any sort of lead, help, guidance would be greatly appreciated. For some reason I just cant interpret pythons built-in list operators into my own methods in LinkedList without having dummy nodes or stored length and an iterator. Looking at it it just seems like I'm so close yet nothing I do or find seems to help. Thank you.
class Node:
def __init__(self, data=None, next=None):
self.data = data
self.next = next
def getData(self):
return self.data
def getNext(self):
return self.next
def setData(self, newdata):
self.data = newdata
def setNext(self, newnext):
self.next = newnext
def __str__(self):
return str(self.data)
def __repr__(self):
return "Node(%s, %s)" % (repr(self.data), repr(self.next))
def __eq__(self, other):
return self.data == other.data and self.next == other.next
class myList:
def __init__(self):
self.first = Node()
def add(self, data):
newNode = Node() # create a new node
newNode.data = data
newNode.next = self.first # link the new node to the 'previous' node.
self.first = newNode # set the current node to the new one
def first(self):
return self.first.data
def __repr__(self):
plist = []
for i in self:
plist.append(i)
return "LinkedList(%s)" % str(plist)
node.setData(5)when you can just normally donode.data = 5. You can also use decorators to wrap variables if you need to control access to them. - Brent Writes Code