I was just playing around in python trying to get a basic sort of linked list working. I was able to make a simple linked list using an article I read online that looks like this:
class node: def __init__(self, value = None, next = None): self.value = value self.next = next def printList(node): print "[", while node: print node, node = node.next print "]" def printBackward(list): if list == None: return head = list tail = list.next printBackward(tail) print head, def removeSecond(list): if list == None: return first = list second = list.next #Make the first node refer to the third first.next = second.next # seperate the second node from the rest of the list second.next = None return second
That just allowed you to make a linked list and remove some elements or print it backwards, simple things like that.
>>> node1 = node(1)
>>> node2 = node(2)
>>> node3 = node(3)
>>> node1.next = node2
>>> node2.next = node3
[ 1 2 3 ]
3 2 1
The problem is that I start to get confused when trying to add elements to the start of the list. I tried to keep using the node class but then add in a linkedList class and an addFirst function, as well as a new function to print the list.
I came up with this:
class node: def __init__(self, value = None, next = None): self.value = value self.next = next def __str__(self): return str(self.value) class linkedList: def __init__(self): self.length = 0 self.head = None def addFirst(list,value): first = node(value) if list.head != None: second = list.head first.next = second list.head == first list.length += 1 def printlst(list): print "[", cursor = list.head while cursor != None: print cursor.value cursor = cursor.next print "]"
I trid to run it by doing something like
>>>newList = linkedList()
Whenever I try that it always just returns me those brackets and I don't quite understand why. If someone could help me figure out a way to set up a linked list and add or remove elements from it without making a specific instance like the "removeSecond" above then I'd really appreciate it.
Also: I've looked into making everything a method and I was not able to figure out what to do, so I'd prefer if someone could explain it in a way that doesn't involve the add functions being methods. Of course you can still give a shot at explaining it to me if you want to.
Thanks for any help in advance.