Cant insert item at start of linked list - python - python-3.x

I'm currently learning about linked lists for a class and ran into trouble.
I have to be able to insert an item before a specified item so
(Apple,banana,pear)before pear would be (Apple,banana,newItem,pear)
and I managed this with this code:
def insert_before(head,data,location):
current = head
found = False
while not found:
if current.next.data == location:
new_node = Node(data)
new_node.next = current.next
current.next = new_node
found = True
else:
current = current.next
But my issue arose when trying to insert an item before the first item in the list, to try this I thought of doing it as such:
if head.data == location:
new_node = Node(data)
head.next = head.next
new_node.next = head`
But this doesn't seem to work. Any guides I found on here were to add an item AFTER the first item, any tips would be appreciated.

In the provided source code, the use of head.next = head.next do nothing and doesn't change the value of the head node.
To modify the value of the first node in a linked list by inserting a new node before, it is necessary update the head variable.
Solution 1 - assign the head as the returned value of the insert_before() function.
The variable previous is used to modify the node before and when is
= None, the first node must be modified.
def insert_before(head,data,location):
current = head
previous = None
found = False
while not found:
if (current != None):
if (current.data == location):
new_node = Node(data)
if (previous != None):
new_node.next = previous.next
previous.next = new_node
else:
new_node.next = head
head = new_node
found = True
else:
previous = current
current = current.next
else:
print('location ',location,' not found.')
break
return head
The use of the function becomes:
myhead = Node(5)
print(myhead.data) # >> 5
myhead = insert_before(myhead,3,5)
print(myhead.data) # >> 3
print(myhead.next.data) # >> 5
Solution 2 - use the OOP of Python by adding a headattribute in the Node class.
The OOP approach is quite similar, but instead of storing the head
node outside the function, the function insert_before() is added to
the class Node.
Step 1 - add in the class Node the attribute head.
class Node(object):
def __init__(self, data=None, next_node=None):
self.data = data
self.next = next_node
self.head = self # store the first node
Step 2 - use the internal self.head instead of the head as parameter
In that case, when the new node shall be inserted before the first
node, the assignment is very simple self.head = new_node.
def Insert_Before(self,data,location):
current = self.head
previous = None
found = False
print('insert ',data,' before ',location)
while not found:
if (current != None):
if (current.data == location):
new_node = Node(data)
if (previous != None):
new_node.next = previous.next
previous.next = new_node
else:
new_node.next = self.head
self.head = new_node # update the first node
found = True
else:
previous = current
current = current.next
else:
print('location ',location,' not found.')
break
return
The use of the function becomes:
myhead = Node(5)
print(myhead.data)
myhead.insert_before(3,5)
print(myhead.head.data)
print(myhead.head.next.data)
Warning: instead of using myhead as the first node, use the
myhead.head attribute.

Related

code should not return any node object(Element)

https://gist.github.com/manaidu-2002/3f7eb60b8521201eba6548ca23cec053
Code returning Node Object(Element), please check the test cases and help me with this
"""Add a couple methods to our LinkedList class,
and use that to implement a Stack.
You have 4 functions below to fill in:
insert_first, delete_first, push, and pop.
Think about this while you're implementing:
why is it easier to add an "insert_first"
function than just use "append"?"""
class Element(object):
def __init__(self, value):
self.value = value
self.next = None
class LinkedList(object):
def __init__(self, head=None):
self.head = head
def append(self, new_element):
current = self.head
if self.head:
while current.next:
current = current.next
current.next = new_element
else:
self.head = new_element
def insert_first(self, new_element):
"Insert new element as the head of the LinkedList"
new_element.next = self.head
self.head = e_insert
def delete_first(self):
"Delete the first (head) element in the LinkedList as return it"
temp = self.head
if temp == None:
return None
s= temp
self.head = temp.next
return s
class Stack(object):
def __init__(self,head=None):
self.ll = LinkedList(head)
def push(self, new_element):
"Push (add) a new element onto the top of the stack"
temp = self.ll.head
while temp.next :
temp = temp.next
temp.next = new_element
def pop(self):
"Pop (remove) the first element off the top of the stack and return it"
if self.ll.head.next == None :
temp = self.ll.head
e= temp
temp = None
return e
elif self.ll.head.next:
temp = self.ll.head
while temp.next.next:
temp = temp.next
e= temp.next
temp.next = None
return e
return None
# Test cases
# Set up some Elements
e1 = Element(1)
e2 = Element(2)
e3 = Element(3)
e4 = Element(4)
# Start setting up a Stack
stack = Stack(e1)
# Test stack functionality
stack.push(e2)
stack.push(e3)
print(stack.pop().value)
print(stack.pop().value)
print(stack.pop().value)
print(stack.pop())
stack.push(e4)
print(stack.pop().value)
First of all, there is an unused name reference in your code: e_insert. This should read new_element.
The main issue is that your Stack class is not re-using the code you already have in your LinkedList class. In the new code you have written there are several mistakes in how you deal with next, but taking a step back, you are making a critical mistake in thinking that the top of the stack should be at the tail of the linked list, but that is very inefficient. The top of the stack should be at the head of the linked list. It is at that side that you can easily remove and insert elements without having to iterate the list.
So take these points into consideration:
Reuse the code you already have for LinkedList. In other words, call the methods defined on the LinkedList class.
The top of the stack is at the head of the linked list.
That means the Stack class can be as simple as this:
class Stack(LinkedList):
def __init__(self, head=None):
self.ll = LinkedList(head)
def push(self, new_element):
self.ll.insert_first(new_element)
def pop(self):
return self.ll.delete_first()

how to make this code short for reverse circular LL in python

class node:
def __init__(self,data):
self.data = data
self.next = None
class circularLL:
def __init__(self):
self.head = None
self.tail = None
def insertNode(self,data):
newnode = node(data)
if self.head is None:
self.head = newnode
self.tail = newnode
else:
newnode.next = self.head
tail = self.tail
tail.next = newnode
self.tail = tail.next
def printCLL(self):
current = self.head
while current.next is not None and current.next is not self.head:
print(current.data, end="----")
current = current.next
print(current.data)
def reverseCLL(self):
head = self.head
tail = self.tail
if head == tail:
return
else:
count = 0
while head.next is not tail:
count +=1
if count ==1:
next = head.next
prev = head
head.next = tail
newtail = head
head = next
else:
next = head.next
head.next = prev
prev = head
head = next
if count is not 0:
next = head.next
head.next = prev
prev = head
tail.next = prev
self.head = tail
self.tail = newtail
else:
head.next = tail
self.tail.next = head
self.head = tail
self.tail = head
c = circularLL()
c.insertNode(1)
c.printCLL()
c.insertNode(2)
c.insertNode(3)
c.insertNode(4)
c.insertNode(5)
c.insertNode(6)
c.printCLL()
c.reverseCLL()
c.printCLL()
I have written a code for circular linkedlist. but I think the reverse part can be shorter so how to make the reverse part short ? and what are the alternative to do this ???
and can any one tell me when I am using the assignment operator for a object then that variable is pointing to that original object or the object copy is assign to the variable's memory location ??
There are still some issues in your code:
When the first node is added, that node's next reference is left to None, which means the list is not really circular. You should actually never have a node whose next reference is None, so I'd suggest to change the Node constructor so that it doesn't assign that value, but instead makes the node self referencing (self.next = self). That also means you can remove most of the None checks from your code.
The printCLL method fails when the list is empty. It should first check that condition.
You should not use is not when comparing with a literal. So instead do if count != 0: or even if count:
Some other remarks:
It is common practice to use PascalCase for class names, so Node instead of node and CircularLL instead of circularLL.
As in a circular, non-empty list the head node is always the one after the tail node, there is no real need to store a separate reference to the head node. You just need self.tail.
As the class name already clearly indicates that we're dealing with a circular linked list, there is no need to have the CLL suffix in the method names. And for a similar reason I'd call the insert method just insert.
Instead of providing a print method, it is probably better practice to provide a __repr__ method, which the native print function will call when it exists.
Make a linked list instance iterable by defining an __iter__ method. Then the above __repr__ can also rely on that.
As to the core of your question: yes this code for reversing a list can be greatly reduced. There is no need to have a counter.
Proposed code:
class Node:
def __init__(self,data):
self.data = data
self.next = self
class CircularLL:
def __init__(self):
self.tail = None
def insert(self, data):
newnode = Node(data)
if self.tail:
newnode.next = self.tail.next
self.tail.next = newnode
self.tail = newnode
def __iter__(self):
if not self.tail:
return
current = self.tail
while current.next is not self.tail:
current = current.next
yield current.data
yield current.next.data
def __repr__(self):
return "----".join(map(repr, self))
def reverse(self):
tail = self.tail
if not tail:
return
prev = tail
curr = prev.next
self.tail = curr
while curr != tail:
curr.next, prev, curr = prev, curr, curr.next
curr.next = prev
c = CircularLL()
c.insert(1)
print(c)
c.insert(2)
c.insert(3)
c.insert(4)
c.insert(5)
c.insert(6)
print(c)
c.reverse()
print(c)

Linked List Implementation Python , printing none as first node

I have created a linked list implementation and everything seems to be working however when I print the linked list it begins with None and then continues to print the numbers accordingly. I am not sure why this happens because if the incoming value is the first value it assigns head to that value
class Node:
def __init__(self,value=None):
self.value = value
self.next = None
class LinkedList:
def __init__(self):
self.head = Node()
def append(self, value):
new_node = Node(value)
new_node.value = value
new_node.next = None
if self.head is None:
self.head = new_node
else:
tmp = self.head
while tmp.next is not None:
tmp = tmp.next
tmp.next = new_node
def show(self):
start = self.head
while start.next is not None:
print(start.value," -> ",end="")
start = start.next
print(start.value)
linked_list = LinkedList()
linked_list.append(4)
linked_list.append(3)
linked_list.append(8)
linked_list.append(2)
linked_list.append(9)
linked_list.show()
You set self.head = Node() in the __init__ function, which would make the first value in your linkedlist None. Maybe you meant to set self.head = None?
In LinkedList constructor you have set self.head=Node(). you may replace it with None but it throws an error or it runs infintly.
In def show(self): point the start node (val=None) to the next node i.e start=self.head.next
start=self.head
None -> 4 -> 3 -> 8 -> 2 -> 9
After moving the pointer
start=self.head.next
4 -> 3 -> 8 -> 2 -> 9

Understanding the "self" in classes for Python

I'm trying to understand the solution provided for reversing a linked list. In particular, I don't get why for the very last line we write:
self.head=prev
and not
current=prev
since
current=self.head
I know my reasoning is flawed, that's why I came here for help. Thank you in advance.
class Node:
# Constructor to initialize the node object
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
# Function to initialize head
def __init__(self):
self.head = None
def reverse(self):
prev = None
current = self.head
while(current is not None):
next = current.next
current.next = prev
prev = current
current = next
self.head = prev
= is not equality like in math, it is the assignment/binding operator.
Therefore, after:
current=self.head
current=prev
current will have the value of prev and self.head will have nothing to do with current nor will be modified.

reverse a linked list non recursive

Please check the reverse function below. The rest of the code should be fine. The function is not reversing the doubly linked list for some reason.
#!/bin/python3
import math
import os
import random
import re
import sys
Doubly linked list Node structure
class DoublyLinkedListNode:
def __init__(self, node_data):
self.data = node_data
self.next = None
self.prev = None
Doubly linked list structure
class DoublyLinkedList:
def __init__(self):
self.head = None
self.tail = None
def insert_node(self, node_data):
node = DoublyLinkedListNode(node_data)
if not self.head:
self.head = node
else:
self.tail.next = node
node.prev = self.tail
self.tail = node
Prints the doubly linked list from head to the tail in order.
def print_doubly_linked_list(node, sep, fptr):
while node:
fptr.write(str(node.data))
node = node.next
if node:
fptr.write(sep)
Please check the below reverse function as this function does not return the reversed doubly linked list. Check for any errors and let me know.
def reverse(head):
if head == None:
return head
temp = None
curr = head
while(curr is not None):
temp = curr.prev
curr.prev = curr.next
curr.next= temp
curr = curr.next
if temp is not None:
head = temp.prev
return head
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
t = int(input())
for t_itr in range(t):
llist_count = int(input())
llist = DoublyLinkedList()
for _ in range(llist_count):
llist_item = int(input())
llist.insert_node(llist_item)
llist1 = reverse(llist.head)
print_doubly_linked_list(llist1, ' ', fptr)
fptr.write('\n')
fptr.close()
You start reversing your list from the head, which has no prev item and therefore breaks out of your while loop. Instead, reversing from the tail should do:
llist1 = reverse(llist.tail)
In general, I think your function reverse should take the whole list (not the head or tail) as an argument, and then build a completely new DoublyLinkedList from the items in it. That would also solve the confusion with your variable names, where llist is a DoublyLinkedList while llist1 is a DoublyLinkedListNode.
edit:
I forgot, in insert_node, you should also make self.tail = node if there hasn't been a head yet / first node.

Resources