Inserting Node at a specific location python - python

This question is a hackerrank challenge. link here: https://www.hackerrank.com/challenges/insert-a-node-at-a-specific-position-in-a-linked-list
"""
Insert Node at a specific position in a linked list
head input could be None as well for empty list
Node is defined as
class Node(object):
def __init__(self, data=None, next_node=None):
self.data = data
self.next = next_node
return back the head of the linked list in the below method.
"""
#This is a "method-only" submission.
#You only need to complete this method.
def InsertNth(head, data, position):
node = head
if position == 0:
node = Node(data)
node.data = data
node.next = head
return node
else:
while position > 0:
node = node.next
i = node.next
node.next = Node(data)
node.next.next = i
return head
my current output is 321024, but I need it to be 310542. Any help is greatly appreciated!

def InsertNth(head, data, position):
start = head
if position == 0:
return Node(data, head)
while position > 1:
head = head.next
position -= 1
head.next = Node(data, head.next)
return start
I didn't test it, but something like this should be right. You first want to save a copy of the reference to the start of the list. Then, you should check if this is being added to the front of the list, in which case you should return a new starting node with the proper value. Otherwise, you cycle through the list until you get to the position you want at which point you set the next node to have the proper value and remaining list.

def insertNodeAtPosition(head, data, position):
prev_node = head
if position == 0:
new_node = SinglyLinkedListNode(data)
new_node.next = head
return new_node
while prev_node is not None:
new_node = SinglyLinkedListNode(data)
for _ in range(position-1):
prev_node = prev_node.next
new_node.next = prev_node.next
prev_node.next = new_node
return head

We have 2 possible options.
If the data should be add in the first (position = 0) and then we should change the head pointer to the current node or
The position should be added in the k-th place and we update the list using the head.next and position-1 recursively
def insertNodeAtPosition(self, head, data, position):
if (position == 0) | (head==None):
return SinglyLinkedListNode(data, head)
else:
head.next = self.insertNodeAtPosition(head.next, data, position-1)
return head

def InsertNth(head, data, position):
node = head
i = 0
temp = Node(data)
while node is not None:
if i == at:
temp.nextnode = node.nextnode
node.nextnode = temp
break
i += 1
node = node.nextnode

class SinglyLinkedListNode:
def __init__(self, node_data):
self.data = node_data
self.next = None
class SinglyLinkedList:
def __init__(self):
self.head = None
self.tail = None
def insertNodeAtPosition(head, data, position):
pos = 0
current_head = head
previous_head = head
while pos <= position:
if pos == position:
new_head = SinglyLinkedListNode(data)
previous_head.next = new_head
new_head.next = current_head
return head
else:
pos += 1
previous_head = current_head
current_head = current_head.next
return head

def insertNodeAtPosition(head, data, position):
currNode = head
while position > 1:
position -= 1
currNode = currNode.next
temp = currNode
node = SinglyLinkedListNode(data)
node.next = temp.next
currNode.next = node
return head

def insertNodeAtPosition(head, data, position):
positer = 0
temp = head
while temp:
if positer == position-1:
newNode = SinglyLinkedListNode(data)
newNode.next = temp.next
temp.next = newNode
break
else:
positer+=1
temp = temp.next
return head

def insert_after(self, data, pos):
new_node = Node(data)
prev = self.head
pos = pos - 1
if pos == 0:
self.insert_front(data)
return
while pos > 1:
prev = prev.next
pos -= 1
new_node.next = prev.next
prev.next = new_node

Here is a recursive solution in opposition to the naive implementation
def insertNodeAtPosition(node, data, position):
if not node:
return None
if position <= 1:
new_node = SinglyLinkedListNode(data)
new_node.next = node.next
node.next = new_node
return node
node.next = insertNodeAtPosition(node.next, data, position - 1)
return node

def insert(self, data, position):
counter = 1
current = self.head
if position > 1:
while current and counter < position:
if counter == position - 1:
data.next = current.next
current.next = data
current = current.next
counter += 1
elif position == 1:
data.next = self.head
self.head = new_element

Related

Merging 2 Linkedlists in python NOT working. Third Linked List created is giving me a NULL value/result after execution

I'm currently stuck on this python exercise where I have 2 LinkedLists (linked_list_1,linked_list_2) which I have to merge together in a new LinkedList. I have tried this code but it keeps giving me a null value for the third LinkedList when I need it to give me the data in both linkedLists. The function is called: merge_linked_lists(linked_list_1, linked_list_2). That's where my problem is. I would be really grateful if someone can help.
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('')
def merge_linked_lists(linked_list_1, linked_list_2):
def merge(List_1, List_2):
head_ptr = temp_ptr = Node() # head_ptr will be the head node of the output list
# temp_ptr will be used to insert nodes in the output list
# Loop for merging two lists
# Loop terminates when both lists reaches to its end
while List_1 or List_2:
# List_1 has not reached its end
# and List_2 has either reached its end or its current node has data
# greater than or equal to the data of List_1 node
# than insert List_1 node in the ouput list
if List_1 and (not List_2 or List_1.data <= List_2.data):
temp_ptr.next = Node(List_1.data)
List_1 = List_1.next
# otherwise insert List_2 node in the ouput list
else:
temp_ptr.next = Node(List_2.data)
List_2 = List_2.next
# move temp_pointer to next position
temp_ptr = temp_ptr.next
# return output list
return head_ptr.next
merge(linked_list_1.head, linked_list_2.head)
# Test merge() function
LL1 = LinkedList()
LL1.add_at_head(Node(2))
LL1.add_at_head(Node(4))
LL1.add_at_head(Node(6))
LL1.add_at_head(Node(8))
LL2 = LinkedList()
LL2.add_at_head(Node(1))
LL2.add_at_head(Node(3))
LL2.add_at_head(Node(5))
LL2.add_at_head(Node(7))
# Merge Function
LL3 = LinkedList()
LL3.head = merge_linked_lists(LL1, LL2)
LL3.print_list()
EDIT 1:
To anyone who wants to know the output, I tried this code on my IDE (Pycharm) and it gave an empty output/result. I also tried it on pythontutor (It visuals i/o there) and I saw that linked_list_1 and linked_list_2 haven't changed but the third linked list was null. Also during the execution, the third linkedlist was able to merge them together but it had an extra node which was the first node (head) and it had NONE as data.
EDIT 2:
The code finally worked!
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('')
def sortList(self):
#Node current will point to head
current = self.head;
index = None;
if(self.head == None):
return;
else:
while(current != None):
#Node index will point to node next to current
index = current.next;
while(index != None):
#If current node's data is greater than index's node data, swap the data between them
if(current.data > index.data):
temp = current.data;
current.data = index.data;
index.data = temp;
index = index.next;
current = current.next;
def merge_linked_lists(linked_list_1, linked_list_2):
linked_list_1.sortList()
linked_list_2.sortList()
def merge(List_1, List_2):
head_ptr = temp_ptr = Node() # head_ptr will be the head node of the output list
# temp_ptr will be used to insert nodes in the output list
# Loop for merging two lists
# Loop terminates when both lists reaches to its end
while List_1 or List_2:
# List_1 has not reached its end
# and List_2 has either reached its end or its current node has data
# greater than or equal to the data of List_1 node
# than insert List_1 node in the ouput list
if List_1 and (not List_2 or List_2.data >= List_1.data):
temp_ptr.next = Node(List_1.data)
List_1 = List_1.next
# otherwise insert List_2 node in the ouput list
else:
temp_ptr.next = Node(List_2.data)
List_2 = List_2.next
# move temp_pointer to next position
temp_ptr = temp_ptr.next
# return output list
return head_ptr.next
return merge(linked_list_1.head, linked_list_2.head)
# Test merge() function
LL1 = LinkedList()
LL1.add_at_head(Node(2))
LL1.add_at_head(Node(4))
LL1.add_at_head(Node(6))
LL1.add_at_head(Node(8))
LL2 = LinkedList()
LL2.add_at_head(Node(1))
LL2.add_at_head(Node(3))
LL2.add_at_head(Node(5))
LL2.add_at_head(Node(7))
# Merge Function
LL3 = LinkedList()
LL3.head = merge_linked_lists(LL1, LL2)
LL3.print_list()
Ps: I also made another code which also worked.
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 sortList(self):
# Node current will point to head
current = self.head;
index = None;
if (self.head == None):
return;
else:
while (current != None):
# Node index will point to node next to current
index = current.next;
while (index != None):
# If current node's data is greater than index's node data, swap the data between them
if (current.data < index.data):
temp = current.data;
current.data = index.data;
index.data = temp;
index = index.next;
current = current.next;
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('')
def merge_linked_lists(linked_list_1, linked_list_2):
linked_list_1.sortList()
linked_list_2.sortList()
LL3 = LinkedList()
node = linked_list_2.head
node1 = linked_list_1.head
if node is None and node1 is None:
return LL3
while True:
if node1 is None:
LL3.add_at_head(Node(node.data))
node = node.next
if node is None:
return LL3
else:
continue
if node is None:
LL3.add_at_head(Node(node1.data))
node1 = node1.next
if node1 is None:
return LL3
else:
continue
if node.data > node1.data:
LL3.add_at_head(Node(node.data))
node = node.next
if node1.data > node.data:
LL3.add_at_head(Node(node1.data))
node1 = node1.next
return LL3
# Test merge() function
# Linked List with even numbers
LL1 = LinkedList()
LL1.add_at_head(Node(2))
LL1.add_at_head(Node(4))
LL1.add_at_head(Node(6))
LL1.add_at_head(Node(8))
# Linked List with odd numbers
LL2 = LinkedList()
LL2.add_at_head(Node(1))
LL2.add_at_head(Node(3))
LL2.add_at_head(Node(5))
LL2.add_at_head(Node(7))
# Merge Function
LL3 = LinkedList()
LL3 = merge_linked_lists(LL1, LL2)
LL3.print_list()
Your merge function has no return statement:
Change:
merge(linked_list_1.head, linked_list_2.head)
to:
return merge(linked_list_1.head, linked_list_2.head)
Another issue is that the sort order of your two input lists is descending, while your merge function assumes they are sorted ascending. So as a result your merged list is not sorted.
So either initialise your lists to be ascending in order (remember you insert values in reversed order) or change <= to >= in your merge function.

AttributeError: 'NoneType' object has no attribute 'next' and Function missing 2 required positional arguments: 'x' and 'y'

I am trying to write a program to insert a node at a specific position and the errors I am getting are,
AttributeError: 'NoneType' object has no attribute 'next'
and also
Function missing 2 required positional arguments: 'x' and 'y'
Code:
class SinglyLinkedListNode:
def __init__(self, data):
self.data = data
self.next = None
class SinglyLinkedList:
def __init__(self):
self.head = None
self.tail = None
def insertnode_end(self, data):
node = SinglyLinkedListNode(data)
if not self.head:
self.head = node
else:
self.tail.next = node
self.tail = node
def print_ll(self):
temp = self.head
while temp is not None:
print(temp.data, end=" ")
temp = temp.next
def insertNode_pos(self, data, pos):
new_node = SinglyLinkedListNode(data)
if (pos == 0):
new_node.next = self.head
self.head = new_node
temp = self.head
while temp.next is not None:
for _ in range(pos - 1):
temp = temp.next
new_node.next = temp.next
temp.next = new_node
llist_count = int(input())
llist = SinglyLinkedList()
for _ in range(llist_count):
llist_item = int(input())
llist.insertnode_end(llist_item)
data = int(input())
pos = int(input())
llist.insertNode_pos(data, pos)
llist.print_ll()
I don't see x and y in your code. It is helpful if you include the full traceback. It seems that your function is hitting the last node in the list, whose next item is None. Obviously, None doesn't have the next and data attributes.
Meanwhile, I modified your insertNode_pos function. One important line here is return if pos == 0. Your function doesn't need to continue in that case.
def insertNode_pos(self, data, pos):
new_node = SinglyLinkedListNode(data)
if pos == 0:
new_node.next = self.head
self.head = new_node
return
temp = self.head
for iter in range(pos):
if iter == 0:
temp = self.head
else:
temp = temp.next
new_node.next = temp.next
temp.next = new_node
One more note is that implementing __str__ is a more common practice for printing content of your data:
def __str__(self):
output = []
temp = self.head
while temp is not None:
output.append(str(temp.data))
temp = temp.next
return ",".join(output)
Then you can simply say print(llist)

Python Linked List Implemention - Inserting node at nth position ? Why the code is not working?

Code Image
class Node:
def __init__(self,data):
self.data = data
self.address = None
class LinkedList:
def __init__(self):
self.start = None
def insert_at_position(self,position,data):
node = Node(data)
i = 0
temp = self.start
while(i<position-1 and temp!=None):
i +=1
temp = temp.address
t1 = node
t1.address = temp
temp = t1
You can try this below assuming 0th position is the head of the LinkedList :
def insert_at_nth_pos(self, position, data):
temp = self.start
if position == 0:
new_node = Node(data)
new_node.address = self.head
self.head = new_node
return
for i in range(1, position-1):
temp = temp.address
if temp is None:
print("Position out of Bounds")
return
if temp.address is None:
temp.address = Node(data)
else:
new_node = Node(data)
new_node.address = temp.address
temp.address = new_node

Double Linked List Middle Insert doesn't work

import math
class Node:
def __init__(self, val, next = None, prev = None):
self.data = val
self.next = next
self.prev = prev
class LinkedList:
def __init__(self):
self.head = None
self.tail = None
self.count = 0
def StartInsert(self, val):
newNode = Node(val)
if self.count == 0:
self.head = newNode
self.tail = newNode
else:
self.head.prev = newNode
newNode.next = self.head
self.head = newNode
self.count += 1
def EndInsert(self, val):
newNode = Node(val)
if self.count == 0:
self.head = newNode
self.tail = newNode
else:
self.tail.next = newNode
newNode.prev = self.tail
self.tail = newNode
self.count += 1
def MiddleInsert(self, val):
newNode = Node(val)
if self.count == 0:
self.head = newNode
self.tail = newNode
else:
index = math.ceil(self.count/2)-1
temp = self.head
while index > 0:
temp = temp.next
index -= 1
temp.next = Node(val, temp.next)
temp.prev = Node(temp.prev.data, temp)
self.count +=1
def delete(self, val):
curNode = self.head
while curNode != None:
if curNode.data == val:
if curNode.prev != None:
curNode.prev.next = curNode.next
else:
self.head = curNode.next
if curNode.next != None:
curNode.next.prev = curNode.prev
else:
self.tail = curNode.prev
self.count -= 1
curNode = curNode.next
def reverse(self):
temp = None
current = self.head
while current != None:
temp = current.prev
current.prev = current.next
current.next = temp
current = current.prev
if temp:
self.head = temp.prev
self.tail = temp.next
def traverse(self):
s = ""
p = self.head
while p is not None:
s += str(p.data) + ' ';
p = p.next
print(s + "| count: " + str(self.count))
list = LinkedList()
list.EndInsert("a")
list.StartInsert("b")
list.StartInsert("c")
list.EndInsert("d")
list.MiddleInsert("c")
list.traverse()
list.reverse()
list.traverse()
Middle Insert gives correct return but doesn't stop. I did the same method for singly linked list but it doesn't seem to work properly for double linked list. It returns proper value but keep getting stuck at the while loop.
I am trying to figure how to connect the newNode(). Please help me by showing code and the reason I get such error.
Thank you so much for helping.
An initial error is that you are creating more Node that necessarily in your MiddleInsert method.
This can lead you to finding the error in your code.
After removing these extra creations, you should simply switch the prev and next pointers, checking that the temp is not actually the last element:
def MiddleInsert(self, val):
newNode = Node(val)
if self.count == 0:
self.head = newNode
self.tail = newNode
else:
index = math.ceil(self.count/2)-1
temp = self.head
while index > 0:
temp = temp.next
index -= 1
newNode.next = temp.next
temp.next = newNode
newNode.prev = temp
if newNode.next is not None:
newNode.next.prev = newNode
self.count +=1
In a doubly linked list, you must maintain prev and next pointers. In MiddleInsert, once you have selected the element that you want to add the new node after, you must insert the new element between that one and its follower.
Let us call C the new node, A the selected node and say B=A.next. Before insertion, you have A.next == B and B.prev == A ; after insertion, you want to have
A.next == C, C.prev == A, C.next == B and B.prev == C.
Just write that in MiddleInsert (unrelated, but no need for the math module here, and for ... in range(...) is the Pythonic way for counting loops):
def MiddleInsert(self, val):
newNode = Node(val)
if self.count == 0:
self.head = newNode
self.tail = newNode
elif self.count == 1:
self.tail = newNode
self.head.next = newNode
newNode.prev = self.head
else:
index = (self.count-1) // 2
temp = self.head
for i in range(index):
temp = temp.next
temp.next.prev = newNode
newNode.next = temp.next
newNode.prev = temp
temp.next = newNode
self.count +=1

Linked List in Python- Append, Index, Insert, and Pop functions. Not sure with code/errors

This assignment asks us to implement the append, insert, index and pop methods for an unordered linked-list.
(What I have so far)
def main():
class Node:
def __init__(self, data):
self.data = data
self.next_node = None
class LinkedList:
def __init__(self):
self.head = None
self.tail = None
def AppendNode(self, data):
new_node = Node(data)
if self.head == None:
self.head = new_node
if self.tail != None:
self.tail.next = new_node
self.tail = new_node
def PrintList( self ):
node = self.head
while node != None:
print (node.data)
node = node.next
def PopNode( self, index ):
prev = None
node = self.head
i = 0
while ( node != None ) and ( i < index ):
prev = node
node = node.next
i += 1
if prev == None:
self.head = node.next
else:
prev.next = node.next
list = LinkedList()
list.AppendNode(1)
list.AppendNode(2)
list.AppendNode(3)
list.AppendNode(4)
list.PopNode(0)
list.PrintList( )
The output so far:
2
3
4
Traceback (most recent call last):
File "<pyshell#32>", line 1, in <module>
main()
File "<pyshell#31>", line 50, in main
list.PrintList( )
File "<pyshell#31>", line 27, in PrintList
node = node.next
AttributeError: 'Node' object has no attribute 'next'
I'm not sure why i'm getting the errors, since the code is technically working. Also any input on the insert, and index functions would be greatly appreciated.
For insert and index methods you will need another Node attribute, because you'll need to keep track of which item is on what position. Let we call it position. Your Node class will now look like this:
class Node:
def __init__(self, data, position = 0):
self.data = data
self.next_node = None
self.position = position
Retrieving index value now is easy as:
def index(self,item):
current = self.head
while current != None:
if current.data == item:
return current.position
else:
current = current.next
print ("item not present in list")
As for the list-altering methods, I would start with a simple add method which adds items to the leftmost position in the list:
def add(self,item):
temp = Node(item) #create a new node with the `item` value
temp.next = self.head #putting this new node as the first (leftmost) item in a list is a two-step process. First step is to point the new node to the old first (lefmost) value
self.head = temp #and second is to set `LinkedList` `head` attribute to point at the new node. Done!
current = self.head #now we need to correct position values of all items. We start by assigning `current` to the head of the list
self.index_correct(current) #and we'll write helper `index_correct` method to do the actual work.
current = self.head
previous = None
while current.position != self.size() - 1:
previous = current
current = current.next
current.back = previous
self.tail = current
What shall the index_correct method do? Just one thing - to traverse the list in order to correct index position of items, when we add new items (for example: add, insert etc.), or remove them (remove, pop, etc.). So here's what it should look like:
def index_correct(self, value):
position = 0
while value != None:
value.position = position
position += 1
value = value.next
It is plain simple. Now, let's implement insert method, as you requested:
def insert(self,item,position):
if position == 0:
self.add(item)
elif position > self.size():
print("position index out of range")
elif position == self.size():
self.AppendNode(item)
else:
temp = Node(item, position)
current = self.head
previous = None
while current.position != position:
previous = current
current = current.next
previous.next = temp
temp.next = current
temp.back = previous
current.back = temp
current = self.head
self.index_correct(current)
Below is the implementation that I could come up with (tested and working). It seems to be an old post, but I couldn't find the complete solution for this anywhere, so posting it here.
# add -- O(1)
# size -- O(1) & O(n)
# append -- O(1) & O(n)
# search -- O(n)
# remove -- O(n)
# index -- O(n)
# insert -- O(n)
# pop -- O(n) # can be O(1) if we use doubly linked list
# pop(k) -- O(k)
class Node:
def __init__(self, initdata):
self.data = initdata
self.next = None
def getData(self):
return self.data
def getNext(self):
return self.next
def setNext(self, newnext):
self.next = newnext
class UnorderedList:
def __init__(self):
self.head = None
self.tail = None
self.length = 0
def isEmpty(self):
return self.head is None
def add(self, item):
temp = Node(item)
temp.setNext(self.head)
self.head = temp
if self.tail is None:
self.tail = temp
self.length += 1
def ssize(self): # This is O(n)
current = self.head
count = 0
while current is not None:
count += 1
current = current.getNext()
return count
def size(self): # This is O(1)
return self.length
def search(self, item):
current = self.head
found = False
while current is not None and not found:
if current.getData() == item:
found = True
else:
current = current.getNext()
return found
def remove(self,item):
current = self.head
previous = None
found = False
while current is not None and not found:
if current.getData() == item:
found = True
else:
previous = current
current = current.getNext()
if previous == None:
# The item is the 1st item
self.head = current.getNext()
else:
if current.getNext() is None:
self.tail = previous # in case the current tail is removed
previous.setNext(current.getNext())
self.length -= 1
def __str__(self):
current = self.head
string = '['
while current is not None:
string += str(current.getData())
if current.getNext() is not None:
string += ', '
current = current.getNext()
string += ']'
return string
def sappend(self, item): # This is O(n) time complexity
current = self.head
if current:
while current.getNext() is not None:
current = current.getNext()
current.setNext(Node(item))
else:
self.head = Node(item)
def append(self, item): # This is O(1) time complexity
temp = Node(item)
last = self.tail
if last:
last.setNext(temp)
else:
self.head = temp
self.tail = temp
self.length += 1
def insert(self, index, item):
temp = Node(item)
current = self.head
previous = None
count = 0
found = False
if index > self.length-1:
raise IndexError('List Index Out Of Range')
while current is not None and not found:
if count == index:
found = True
else:
previous = current
current = current.getNext()
count += 1
if previous is None:
temp.setNext(self.head)
self.head = temp
else:
temp.setNext(current)
previous.setNext(temp)
self.length += 1
def index(self, item):
pos = 0
current = self.head
found = False
while current is not None and not found:
if current.getData() == item:
found = True
else:
current = current.getNext()
pos += 1
if not found:
raise ValueError('Value not present in the List')
return pos
def pop(self, index=None):
if index is None:
index = self.length-1
if index > self.length-1:
raise IndexError('List Index Out Of Range')
current = self.head
previous = None
found = False
if current:
count = 0
while current.getNext() is not None and not found:
if count == index:
found = True
else:
previous = current
current = current.getNext()
count += 1
if previous is None:
self.head = current.getNext()
if current.getNext() is None:
self.tail = current.getNext()
else:
self.tail = previous
previous.setNext(current.getNext())
self.length -= 1
return current.getData()
def insert(self,item,position):
if position==0:
self.add(item)
elif position>self.size():
print("Position index is out of range")
elif position==self.size():
self.append(item)
else:
temp=Node.Node(item,position)
current=self.head
previous=None
current_position=0
while current_position!=position:
previous=current
current=current.next
current_position+=1
previous.next=temp
temp.next=current
Notice that in the Node class you defined the "next" field as "next_node". Therefore the interpreter doesn't know "next". So, instead of node.next it should be node.next_node

Categories

Resources