For practice and to prepare for programming interviews I've by doing problem sets from cracking the interview by Gayle McDowell. That being said I've been answering all the problems in both Python and Java. I'm working with linked list in python at the moment, since i've completed it all in Java already. I'm having trouble adding cargo/node data to the end/tail of my linked list. This was not a problem in Java and I suppose my first mistake is that I'm trying to implement this method the same way I did in Java.
The is the method I need help with
def append(self, data):.
new_node = Node()
new_node = data
node = self.cur_node
while node:
node = node.next
node.next = new_node
The problem i'm having is that node.next is set to None after the while loop. I thought that if I iterated over the linked list and added my data the to tail end this is how I would go about it. I assumptions are largely based on how I implemented it in Java which I added below just for reference.
void appendToTail(int d){
Node end = new Node(d); //Item to append to the end
Node n = this; //To access Class object next
while(n.next != null){
n = n.next;
}
n.next = end;
}
The rest of my python class looks like this, just incase you need to see how the rest of the link list is implemented.
class Node(object):
def __init__(self):
self.data = None
self.next = None
class LinkedList(object):
def __init__(self):
self.cur_node = None
def add(self, data):
new_node = Node()
new_node.data = data
new_node.next = self.cur_node
self.cur_node = new_node
#write a method that appends to the tail instead of the head
def append(self, data):.
new_node = Node()
new_node.data = data
node = self.cur_node
while node:
node = node.next
node.next = new_node #This is the problem line
def list_print(self):
node = self.cur_node # cant point to ll!
while node:
print node.data,
node = node.next
# answer to question 2_1
# Write code to remove duplicates from an unsorted linked list
def remove_dup(self):
lset = set()
previous = Node()
node = self.cur_node
while node:
if node.data in lset:
previous.next = node.next
else:
lset.add(node.data)
previous = node
node = node.next
I would love some direction on how to go about fixing or changing my append method.
while node:towhile node.next:, but I'm going to test this to be sure.new_node = Node()and then immediately throwing that away withnew_node = data? Is that supposed to benew_node.data = dataor something like that?