Delete without head pointer
You are given a pointer/ reference to the node which is to be deleted from the linked list of N nodes. The task is to delete the node. Pointer/ reference to head node is not given.
Note: No head reference is given to you. It is guaranteed that the node to be deleted is not a tail node in the linked list.
Example 1:
Input:
N = 2
value[] = {1,2}
node = 1
Output: 2
Explanation: After deleting 1 from the
linked list, we have remaining nodes
as 2.
Example 2:
Input:
N = 4
value[] = {10,20,4,30}
node = 20
Output: 10 4 30
Explanation: After deleting 20 from
the linked list, we have remaining
nodes as 10, 4 and 30.
Your Task:
You only need to complete the function deleteNode that takes reference to the node that needs to be deleted. The printing is done automatically by the driver code.
answer'''
class Solution:
#Function to delete a node without any reference to head pointer.
def deleteNode(self,curr_node):
temp=curr_node.next
curr_node.data=temp.data
curr_node.next=temp.next
del temp
#{
# Driver Code Starts
#Initial Template for Python 3
#Contributed by : Nagendra Jha
import atexit
import io
import sys
sys.setrecursionlimit(5000)
_INPUT_LINES = sys.stdin.read().splitlines()
input = iter(_INPUT_LINES).__next__
_OUTPUT_BUFFER = io.StringIO()
sys.stdout = _OUTPUT_BUFFER
@atexit.register
def write():
sys.__stdout__.write(_OUTPUT_BUFFER.getvalue())
# Node Class
class Node:
def __init__(self, data): # data -> value stored in node
self.data = data
self.next = None
# Linked List Class
class LinkedList:
def __init__(self):
self.head = None
self.tail = None
# creates a new node with given value and appends it at the end of the linked list
def append(self, new_value):
new_node = Node(new_value)
if self.head is None:
self.head = new_node
self.tail =new_node
return
self.tail.next=new_node
self.tail=new_node
def getNode(self,value): # return node with given value, if not present return None
curr_node=self.head
while(curr_node.next and curr_node.data != value):
curr_node=curr_node.next
if(curr_node.data==value):
return curr_node
else:
return None
# prints the elements of linked list starting with head
def printList(self):
if self.head is None:
print(' ')
return
curr_node = self.head
while curr_node:
print(curr_node.data,end=" ")
curr_node=curr_node.next
print(' ')
if __name__ == '__main__':
t=int(input())
for cases in range(t):
n = int(input())
a = LinkedList() # create a new linked list 'a'.
nodes = list(map(int, input().strip().split()))
for x in nodes:
a.append(x)
del_elem = int(input())
to_delete=a.getNode(del_elem)
Solution().deleteNode(to_delete)
a.printList()
Comments
Post a Comment