def add(self, value):
#write your code here
if self.head == None:
new_node = Node(value)
self.head = new_node
self.tail = self.head
elif self.head.value > new_node.value:
new_node = Node(value)
new_node.value = value
new_node.next = self.head
self.head = new_node
else:
new_node = Node(value)
self.tail.setNext(new_node)
self.tail = new_node
self.count += 1
Above is the code for my function add. I am trying to add Node objects
into a linked list in ascending order so that when I print it it comes out as:
>>> x.add(8)
>>> x.add(7)
>>> x.add(3)
>>> x.add(-6)
>>> x.add(58)
>>> x.add(33)
>>> x.add(1)
>>> x.add(-88)
>>> print(x)
Head:Node(-88) Tail:Node(58)
List:-88 -6 1 3 7 8 33 58
But when I do it with my code above it prints it out as:
>>> print(x)
Head:Node(-88)
Tail:Node(1)
List:-88 -6 3 7 8 58 33 1
I'm 80% sure the problem is within the elif statement but I am not sure how to fix it to make go in ascending order.
The problem is in the last else.
So let's see what is going on:
number, action, result:
8 -> in the first if -> 8
7 -> in elif 8 > 7 -> 7,8
3,-6 -> same in elif -> -6, 3, 7, 8
58 -> last else -> -6, 3, 7, 8, 58
and here comes the error when 33 comes and enters the last else again since it is bigger than head which is -6, and the result becomes -6, 3, 7, 8, 58, 33.
To fix this you need to loop through the list to see where 33 needs to be placed, you can't have a sorted list just by placing the items at the start or at the end.
def add(self, value):
#write your code here
#if list is empty
if self.head == None:
new_node = Node(value)
self.head = new_node
self.tail = self.head
#elif value < head set new head
elif self.head.value > value:
new_node = Node(value)
new_node.value = value
new_node.next = self.head
self.head = new_node
#elif value > tail set new tail
elif value > self.tail.value:
new_node = Node(value)
self.tail.setNext(new_node)
self.tail = new_node
# and finally you need to loop to find the sweet spot
else:
# we will start the search from the head
current_node = self.head
# while the value we wish to insert is bigger than the next one
while value > current_node.next.value:
# set the current one to the next one
current_node = current_node.next
# finally we reached a node which is smaller than the value we wish to insert
# but its next node is bigger
new_node = Node(value)
# set the new nodes next to the bigger node
new_node.next = current_node.next
# and the curren't node's next to the new one
current_node.next = new_node
Related
I'm creating a single linked list insert beginning, end, and middle of the linked list. After running code inserting the middle is not working in the linked list changing location value randomly and after running it's not getting.
Can anyone suggest what is wrong with the code:
class Node:
def __init__(self, value=None):
self.value = value
self.next = None
class SLinkedList:
def __init__(self):
self.head = None
self.tail = None
def __iter__(self):
node = self.head
while node:
yield node
node = node.next
def insertsll(self, value, location):
new_node = Node(value)
if self.head is None:
self.head = new_node
self.tail = new_node
else:
if location == 0:
new_node.next = self.head
self.head = new_node
elif location == 1:
new_node.next = None
self.tail.next = new_node
self.tail = new_node
else:
temp_node = self.head
index = 0
while index < location - 1:
temp_node = temp_node.next
index += 1
next_node = temp_node.next
temp_node.next = new_node
new_node.next = next_node
# if temp_node == self.tail:
# self.tail = new_node
sll = SLinkedList()
sll.insertsll(1, 1)
sll.insertsll(2, 1)
sll.insertsll(3, 1)
sll.insertsll(4, 1)
sll.insertsll(0, 0)
sll.insertsll(60, 3)---> run this random changing location not working in correct location
sll.insertsll(50, 4)---> run this random changing location not working in correct location
print([node.value for node in sll])
Output:
[0, 1, 50, 2, 3, 4]
Process finished with exit code 0
I think the iteration in the while loop was a little bit too complicated. I think with this code it is more understandable what the insert does. Also, I don't know why you had the location === 1 check. It seems to be not necessary.
class Node:
def __init__(self, value=None):
self.value = value
self.next = None
class SLinkedList:
def __init__(self):
self.head = None
self.tail = None
def __iter__(self):
node = self.head
while node:
yield node
node = node.next
def insertsll(self, value, location):
new_node = Node(value)
if self.head is None:
self.head = new_node
self.tail = new_node
else:
if location == 0:
new_node.next = self.head
self.head = new_node
else:
temp_node = self.head
index = 0
# Iterate to insert location
while index < location - 1:
index += 1
temp_node = temp_node.next
# Insert new node
new_node.next = temp_node.next
temp_node.next = new_node
# Check if new node is tail
if new_node.next is None:
self.tail = new_node
sll = SLinkedList()
sll.insertsll(1, 1)
sll.insertsll(2, 1)
sll.insertsll(3, 1)
sll.insertsll(4, 1)
sll.insertsll(0, 0)
sll.insertsll(60, 3)
sll.insertsll(50, 4)
print([node.value for node in sll])
Output:
[0, 1, 4, 60, 50, 3, 2]
P.S.: Such a structure really benefits from a length attribute. This can be used to check if an insert operation is even allowed. Probably, you should consider adding it.
I'm creating a function that takes in a sorted linked list and a value. I create a new node with the given value by new_node = LN(v). I am trying to return a linked list with the new node in the correct position. The example will help clarify.
Ex)
ll = converts_list_to_linked_list([4, 7, 9, 14]) #I have a linked list: 4->7->9->12->14
The Function:
insert_ordered(ll, 12)
returns a linked list of "4->7->9->12->14->None"
I am completely stuck on how to insert the new node in the correct position. The last else statement in my function is incorrect.
def insert_ordered(ll,x):
new_node = LN(v) #Creates new node
#If given ll is empty, newnode is the linkedlist
if ll == None:
ll = new_node
#Makes new_node the head of ll if first val is >= new_node value.
elif ll.value >= new_node.value:
temp = ll
ll = new_node
ll.next = temp
#[ERROR] Adds new_node between two nodes of ll in sorted order.
else:
while ll.next != None:
if ll.value < new_node.value:
ll = ll.next
new_node.next = ll.next
ll.next = new_node
return ll
After solving this iteratively, is it possible to solve it recursively?
Try this:
class LN:
def __init__(self, value):
self.value = value
self.next = None
def insert_ordered(root, data):
node = LN(data)
if root == None:
return node
else:
if root.value > data:
node.next = root
return node
else:
temp, prev = root, None
while temp.next and temp.value <= data:
prev = temp
temp = temp.next
if temp.next == None and temp.value <= data:
temp.next = node
else:
node.next = prev.next
prev.next = node
return root
root = None
root = insert_ordered(root, 4)
root = insert_ordered(root, 7)
root = insert_ordered(root, 9)
root = insert_ordered(root, 14)
root = insert_ordered(root, 12)
#4->7->9->12->14
I am currently taking an online computer science introductory course and have just learned the concept of a linked list. Though I understand the concept of linked lists, I still am unsure as how to deal with linked lists.
As such, I seek out help in solving the following problem, which will be of significant help for my understanding of linked lists:
Write a function (not in LinkedList class definition) that given a linked list, will change that linked list to filter out odd numbers. Immediately after the function returns, the linked list will only have even numbers.
I am unsure as to how to access the nodes in the list and check whether they are odd or even and remove or keep them accordingly.
I apologize if this seems like a trivial question, but I would appreciate any help that might help me learn.
The code for the linked list and node classes (as provided by the online course):
class Node:
def __init__(self, data=None, next_node=None):
self.data = data
self.next = next_node
def __str__(self):
return str(self.data)
class LinkedList:
def __init__(self):
self.length = 0
self.head = None
def print_list(self):
node = self.head
while node is not None:
print(node, end=' ')
node = node.next
print('')
def add_at_head(self, node):
node.next = self.head
self.head = node
self.length += 1
def remove_node_after(self, node):
if node.next is not None:
temp = node.next
node.next = node.next.next
temp.next = None
self.length -= 1
def remove_first_node(self):
if self.head is None:
return
temp = self.head
self.head = self.head.next
temp.next = None
self.length -= 1
def print_backward(self):
def print_nodes_backward(node):
if node.next is not None:
print_nodes_backward(node.next)
if node is not None:
print(node, end=' ')
if self.head is not None:
print_nodes_backward(self.head)
print('')
Let's say you have a bare-bones simple linked list that looks like this:
class LinkedList:
class ListNode:
def __init__(self, data):
self.data = data
self.next = None
def __init__(self):
self.head = None
def add(self, data):
if self.head is None:
self.head = LinkedList.ListNode(data)
else:
current_node = self.head
while current_node.next is not None:
current_node = current_node.next
current_node.next = LinkedList.ListNode(data)
def __str__(self):
ret = "["
current_node = self.head
while current_node is not None:
ret = ret + str(current_node.data)
if current_node.next is not None:
ret = ret + ", "
current_node = current_node.next
ret = ret + "]"
return ret
In other words, the LinkedList contains a single head, which is a ListNode. Every element in the Linked List is contained in a ListNode, and each ListNode points towards the next element in the list.
As you can see, for adding an element to the list, we either create a node at the head if the list is empty (i.e. self.head is None), or we traverse to the end of the list by continuously jumping to the .next element for each ListNode, starting from the head. We also use this paradigm for printing a string representation of our list.
So, to remove any node from the linked list, we can simply change the node that references it, so that the node we want to remove gets skipped. At which point it will disappear.
To remove all list nodes containing odd-numbered data, we might do something like this:
def remove_odds(self):
# special case: head node
# remove odd head elements by simply setting head to the next element after
while (self.head is not None) and (self.head.data % 2 == 1):
self.head = self.head.next
# regular case: the rest of the nodes
current_node = self.head
while (current_node is not None) and (current_node.next is not None):
# if the next node's data is odd, then
if current_node.next.data % 2 == 1:
# skip that node by pointing this node's .next to the next node's .next
current_node.next = current_node.next.next
# otherwise, move forwards in the list
else:
current_node = current_node.next
Proof of concept:
>>> lst = LinkedList()
>>> lst.add(2)
>>> lst.add(5)
>>> lst.add(6)
>>> lst.add(3)
>>> lst.add(7)
>>> lst.add(8)
>>> lst.add(10)
>>> lst.add(1)
>>> lst.add(4)
>>> print(lst)
[2, 5, 6, 3, 7, 8, 10, 1, 4]
>>> lst.remove_odds()
>>> print(lst)
[2, 6, 8, 10, 4]
Copied from comment: The idea is to iterate through the list head-to-tail while remembering the previous node; when you find a garbage node, apply remove_node_after to the remembered node, or move the head to the current node if we haven't had time to remember anything yet.
The code would be something like this (untested):
class LinkedList:
# ...
def delete_if(self, pred):
prev = None
curr = self.head
while curr:
if pred(curr.data):
if prev:
self.remove_node_after(prev)
else:
self.head = curr
prev = curr
curr = curr.next
llist.delete_if(lambda x: x % 2 == 1) # delete if odd
# Mahmoud AL-Mokdad
# this course on Udemy By SEfactoru right๐
# use my code ๐
def filter_even(ll):
first_node = ll.head
while (first_node is not None) and (first_node.data % 2 != 0):
ll.remove_first_node()
first_node = ll.head
node = first_node
while node is not None and node.next is not None:
if node.next.data % 2 != 0:
ll.remove_node_after(node)
else:
node = node.next
Basically, I'm implementing a LinkedList class and then implementing various methods to use it. Below is the code for the LinkedList class(and its dependent Node class)
# A simple linked list implementation
class Node:
# attributes:
# data (can be anything)
# next (another Node)
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
# attributes:
# head (a Node)
# ****************
# methods:
# insert
# find
# delete
def __init__(self):
self.head = None
def __str__(self):
output = []
current_node = self.head
while current_node:
output.append(str(current_node.data))
current_node = current_node.next
return(", ".join(output))
# Creates a Node with the given data and inserts into the front of the list.
def insert(self, data):
new_node = Node(data)
new_node.next = self.head
self.head = new_node
# Finds the first node with the given data. Returns None if there is no such node.
def find(self, data):
current_node = self.head
while(current_node):
if (current_node.data == data):
return current_node
current_node = current_node.next
return None # We reached the end of the list without finding anything.
# Deletes given node. Can be used in conjunction with find.
def delete(self, deleted_node):
if deleted_node == self.head:
self.head = self.head.next
return
current_node = self.head
while(current_node.next != deleted_node):
current_node = current_node.next
current_node.next = deleted_node.next
Then, I'm trying to implement a rotate(my_list, N) function, which will, well, rotate my_list by N. The following is my code:
import linkedlists as ll
from ErrorHandler import sanitize
import random, math, time, copy
def length(my_list):
sanitize(my_list, ll.LinkedList)
if my_list.head == None: return 0
count = 1 #First item! Ah, ah, ah
current_node = my_list.head
while current_node.next != None:
current_node = current_node.next
count += 1 #One more item! Ah, ah, ah
return count
def get_Nth(my_list, N):
sanitize(my_list, ll.LinkedList)
if my_list.head == None: return None
current_node = my_list.head
count = 0
while current_node.next != None:
if count == N:
return current_node
count +=1
current_node = current_node.next
return current_node
def rotate(my_list, N):
sanitize(my_list, ll.LinkedList)
if my_list.head == None: return None
N = N % length(my_list)
lent = length(my_list)
get_Nth(my_list, lent-1).next = my_list.head
my_list.head = get_Nth(my_list, lent-N)
get_Nth(my_list, lent-N-1).next = None
However, calling rotate() on a LinkedList containing the numbers from 0 to 9 in ascending order returns 8,9,0,1,2,3,4,5. Why? I'm pretty sure it has to do with the third- and second-to-last lines, because when assigning get_Nth(my_list, lent-1).next to my_list.head, it only points to my_list.head, instead of the Node object my_list.head points to at the time.
How can I fix this?
Your error is right here: get_Nth(my_list, lent-N-1).next = None
I'm assuming you called rotate(my_list, 2) so at this point, the list looks like this [8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, ...]. So when you call get_Nth(my_list, lent-N-1), lent-N-1 is 7, and well, the element at index 7 is actually 5.
You should just use lent-1.
I am learning python and data structure. I was implementing singly linked list methods which included inserting at head and at given position. I ended up writing this code :
class Node :
def __init__(self,data=None,next_node=None) :
self.data = data
self.next = next_node
class LinkedList :
def __init__(self) :
self.head = None
def insertathead(self,new_data) :
new_node = Node(new_data)
new_node.next = self.head
self.head = new_node
def InsertNpos(self,new_data,pos):
start = self.head
if pos == 0:
return Node(new_data, self.head)
while pos > 1:
self.head = self.head.next
pos -= 1
self.head.next = Node(new_data, self.head.next)
return start
def PrintLinkList(self) :
temp = self.head
while (temp) :
print (temp.data)
temp = temp.next
if __name__ == '__main__' :
llist = LinkedList()
llist.insertathead(8)
llist.insertathead(3)
llist.insertathead(10)
llist.insertathead(12)
llist.insertathead(15)
llist.insertathead(2)
llist.InsertNpos(1,2)
llist.PrintLinkList()
Output:
15
1
12
10
3
8
Now, just inserting at head works fine but InsertNpos(1,2) gives wrong output. The output is supposed to be 2,15,1,12,10,3,8.Please tell me where my code is wrong.
When you insert at position pos, your insertion routine deletes the first pos-1 elements of the list. It changes the head pointer on each iteration. You need a local variable to iterate through the list. Also, why are you returning a value? You never use it. The only purpose of this method is to update the list in place.
def InsertNpos(self,new_data,pos):
if pos == 0:
self.head = Node(new_data, self.head)
return
start = self.head
while pos > 1:
start = start.next
pos -= 1
start.next = Node(new_data, start.next)
New output:
Before insertion
2
15
12
10
3
8
After insertion
2
15
1
12
10
3
8
Even though the answer has already been accepted, I tried the solution and as AChampion suggested it didn't work for me for inserting at 0, but my solution did:
class Node :
def __init__(self,data=None,next_node=None) :
self.data = data
self.next = next_node
class LinkedList :
def __init__(self) :
self.head = None
def insertathead(self,new_data) :
new_node = Node(new_data)
new_node.next = self.head
self.head = new_node
def InsertNpos(self,new_data,pos):
if pos == 0:
self.head = Node(new_data, self.head)
return self.head
i = 0
curr = self.head
while curr.next:
if i == pos - 1:
curr.next = Node(new_data, curr.next)
return self.head
curr = curr.next
i += 1
curr.next = Node(new_data)
return self.head
def PrintLinkList(self) :
temp = self.head
while (temp) :
print (temp.data)
temp = temp.next
This will insert the item at the end if pos is out of range.
def insertNodeAtPosition(head, data, position):
current = head
if not head:
head = SinglyLinkedListNode(data)
return head
# Shift to element before position i.e. before_node
# Change it to point to new_node
# Set new_node.next to before_node.next
for _ in range(position-1):
current = current.next
temp = current.next
new_node = SinglyLinkedListNode(data)
current.next = new_node
new_node.next = temp
return head