Python insert node function - python

I am having a really hard time understanding how to properly fix my insert node function. I am not receiving any errors but I am also not displaying the list.
class Node:
def __init__(self, data):
self.data = data
self.next = None
class Solution:
def display(self, head):
current = head
while current:
print current.data,
current = current.next
def insert(self, head, data):
self.head = head
new_node = Node(data)
if self.head is None:
self.head = new_node
else:
new_node.next = self.head
self.head = new_node
mylist = Solution()
T = int(input())
head = None
for i in range(T):
data = int(input())
head = mylist.insert(head, data)
mylist.display(head)

Your insert() didn't return anything. So head will be None if you assign returned value to it.

I think this is you want
class Node:
def __init__(self, data):
self.data = data
self.next = None
class Solution:
def __init__(self):
self.head = None
def display(self):
current = self.head
while current:
print current.data,
current = current.next
def insert(self, data):
new_node = Node(data)
if self.head is None:
self.head = new_node
else:
new_node.next = self.head
self.head = new_node
mylist = Solution()
T = int(input())
for i in range(T):
data = int(input())
mylist.insert(data)
mylist.display()

Related

Reversed double linked list by python

why can't print reversed this double linked list by python?
always print 6 or None
please can anyone help me fast to pass this task
///////////////////////////////////////////////////////////////////////////
class Node:
def __init__(self, data=None, next=None, prev=None):
self.data = data
self.next = next
self.previous = prev
sample methods==>
def set_data(self, newData):
self.data = newData
def get_data(self):
return self.data
def set_next(self, newNext):
self.next = newNext
def get_next(self):
return self.next
def hasNext(self):
return self.next is not None
def set_previous(self, newprev):
self.previous = newprev
def get_previous(self):
return self.previous
def hasPrevious(self):
return self.previous is not None
class double===>
class DoubleLinkedList:
def __init__(self):
self.head = None
self.tail = None
def addAtStart(self, item):
newNode = Node(item)
if self.head is None:
self.head = self.tail = newNode
else:
newNode.set_next(self.head)
newNode.set_previous(None)
self.head.set_previous(newNode)
self.head = newNode
def size(self):
current = self.head
count = 0
while current is not None:
count += 1
current = current.get_next()
return count
here is the wrong method ==>
try to fix it without more changes
def printReverse(self):
current = self.head
while current:
temp = current.next
current.next = current.previous
current.previous = temp
current = current.previous
temp = self.head
self.head = self.tail
self.tail = temp
print("Nodes of doubly linked list reversed: ")
while current is not None:
print(current.data),
current = current.get_next()
call methods==>
new = DoubleLinkedList()
new.addAtStart(1)
new.addAtStart(2)
new.addAtStart(3)
new.printReverse()
Your printReverse seems to do something else than what its name suggests. I would think that this function would just iterate the list nodes in reversed order and print the values, but it actually reverses the list, and doesn't print the result because of a bug.
The error in your code is that the final loop has a condition that is guaranteed to be false. current is always None when it reaches that loop, so nothing gets printed there. This is easily fixed by initialising current just before the loop with:
current = self.head
That fixes your issue, but it is not nice to have a function that both reverses the list, and prints it. It is better practice to separate these two tasks. The method that reverses the list could be named reverse. Then add another method that allows iteration of the values in the list. This is done by defining __iter__. The caller can then easily print the list with that iterator.
Here is how that looks:
def reverse(self):
current = self.head
while current:
current.previous, current.next = current.next, current.previous
current = current.previous
self.head, self.tail = self.tail, self.head
def __iter__(self):
node = self.head
while node:
yield node.data
node = node.next
def __repr__(self):
return "->".join(map(repr, self))
The main program can then be:
lst = DoubleLinkedList()
lst.addAtStart(1)
lst.addAtStart(2)
lst.addAtStart(3)
print(lst)
lst.reverse()
print(lst)

Python dictionary with values as singly linked lists

I have been trying to create a Python dictionary with values as singly linked lists. My code looks okay resulting correct keys. However each key yield the same value, do not know why. Please reply if you have any solution, code has been given below.
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def append(self, data):
new_node = Node(data)
if self.head is None:
self.head = new_node
else:
tail = self.head
while tail.next:
tail = tail.next
tail.next = new_node
def create_two_ll(self, lists):
ll_dict = {}
for i in range(len(lists)):
for data in lists[i]:
self.append(data)
ll_dict[f"ll{i}"] = ll
print(ll_dict)
print(ll_dict["ll0"].head.next.next.next.data)
print(ll_dict["ll1"].head.next.next.next.data)
return ll_dict
if __name__ == "__main__":
ll = LinkedList()
ll.create_two_ll([[1,3,5], [2,4,6]])
Output (wrong):
{'ll0': <__main__.LinkedList object at 0x7feead82c850>}
{'ll0': <__main__.LinkedList object at 0x7feead82c850>, 'll1': <__main__.LinkedList object at 0x7feead82c850>}
2
2
i solved it another way but im not sure its ok
i hope it'll trigger better way in your mind
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def append(self, data):
new_node = Node(data)
if self.head is None:
self.head = new_node
else:
tail = self.head
while tail.next:
tail = tail.next
tail.next = new_node
def create_two_ll(self, lists):
ll_dict = {}
for i in range(len(lists)):
for data in lists[i]:
self.append(data)
ll_dict[f"ll{i}"] = data
print(ll_dict)
return ll_dict
if __name__ == "__main__":
ll = LinkedList()
ll.create_two_ll([[1,3,5], [2,4,6],[7,9,11]])

calling a method in another method errors

class Node:
def __init__(self, data):
self.data = data
self.ref = None
class LinkedList:
def __init__(self):
self.head = None
def show(self):
if self.head is None:
print("This linked lists is empty")
else:
currentnode = self.head
while currentnode is not None:
print(currentnode.data, end=" --> ")
currentnode = currentnode.ref
def addelement(self, value):
newnode = Node(value)
newnode.ref = self.head
self.head = newnode
def lenofll(self , i = 0):
while self.head is not None:
i = i +1
self.head = self.head.ref
return i
def middle(self):
i = 0
lent = self.lenofll()
if self.head is None: # self.head changed to None after calling lenofll method.
print("linked list is empty")
I wanted to get the length of linked lists in the middle method. But as I called self.lenofll(), it changed the self.head to None.
What can I do to fix this?
Indeed, doing self.head = self.head.ref modifies the head. You should not make any modifications to self.head in a method whose job is just to search in the list -- without modifying anything to it.
As you can see, that method keeps looping until self.head is not None is not true, i.e. when self.head is None. No wonder that self.head is None after running this method!
Use a local variable for this iteration instead:
def lenofll(self, i = 0):
node = self.head # use local variable
while node is not None:
i += 1
node = node.ref
return i

How to select the first node in linked list?

I want to select the first node in the linked list and present the selected node. This is the whole code that I've created. The "prepend" adds the node before the first node. The "append" adds the node after the last of the linked list.
class Node:
def __init__(self, data=None, next=None):
self.data = data
self.next = next
def __str__(self):
return str(self.data)
# LinkedList definition here
class LinkedList:
def __init__(self):
self.head = None
self.tail = None
def prepend(self, data):
node = Node(data, self.head)
if self.head is None:
self.head = node
self.tail = node
else:
node.next = self.head
self.head = node
def append(self, data):
node = Node(data, None)
if self.tail is None:
# No elements in list
self.head = node
self.tail = node
else:
self.tail.next = node
self.tail = node
def pop_start(self):
if self.head is None:
return None
if self.head.next is None:
cur = self.head
self.head = None
return cur
else:
if self.head != None:
temp = self.head
self.head = self.head.next
return temp
names = LinkedList()
names.append("Bill Gates")
names.append("Steve Jobs")
names.prepend("Jody")
print(names.pop_start())
I can get the result of Jody. But if instead, I test for
print(names.pop_start() == "Jody")
It shows False. What is the reason?
names.pop_start() returns a Node object. Its data is the string 'Jodie', and because of how you've defined its __str__ method, when you print the node, the string is what you'll see. But the node itself is a node, not a string.
If you compare to the data attribute:
print(names.pop_start().data == "Jody")
...you'll get True, as intended. But it would probably make more sense for pop_start to just return the data anyway, rather than the Node object. Here's how you could do that:
def pop_start(self):
if self.head is None:
return None
else:
data = self.head.data
if self.head is self.tail:
self.tail = None
self.head = self.head.next
return data

why the element not appending in linked list?

not getting expected output. Missing node with data = 6
looks like not insertAfter method properly,
cant find the issue.
pls suggest any other issue too as i am just started with data structures. is there anything need to be kept in mind while studying data structures.
class Node:
def __init__(self,data):
self.data = data
self.next = None
class LinkeList:
def __init__(self):
self.head = None
def push(self,new_data):
new_node = Node(new_data)
new_node.next = self.head
self.head = new_node
def insertAfter(self,prev_node,new_data):
new_node = Node(new_data)
if self.head is None:
self.head = new_node
return
new_node.next = prev_node.next
prev_node.next = new_node
def append(self,new_data):
new_node = Node(new_data)
if self.head is None:
self.head = new_node
return
last = self.head
while last.next != None:
last = last.next
last.next = new_node
def printList(self):
temp = self.head
while temp is not None:
print(temp.data, end = " ")
temp = temp.next
if __name__ =='__main__':
llist = LinkedList()
llist.append(7)
llist.append(8)
llist.push(5)
llist.insertAfter(Node(5),6)
llist.printList()
So the issue is in this line,
llist.insertAfter(Node(5),6)
When you do insertAfter then you need to first get a Node from the current linked list, rather what you are doing is, that you create a new node, then pass it. That new node might have the same value as a . node in your linked list, but it really isn't a part of it, what you need to do is as follows
First implement a get node function, that gets a node from the linked list with the value that you want, something like this
def getNode(self, value):
temp = self.head
while temp is not None:
if temp.value == value:
return temp
else:
temp = temp.next
return None
then do this.
llist.insertAfter(llist.getNode(5),6)
Also put a check for if passed node is not None in insertAfter

Categories