-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdelete_node_without_head_pointer.py
More file actions
104 lines (87 loc) · 2.39 KB
/
delete_node_without_head_pointer.py
File metadata and controls
104 lines (87 loc) · 2.39 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
#User function Template for python3
'''
Your task is to delete the given node from
the linked list, without using head pointer.
Function Arguments: node (given node to be deleted)
Return Type: None, just delete the given node from the linked list.
{
# Node Class
class Node:
def __init__(self, data): # data -> value stored in node
self.data = data
self.next = None
}
Contributed By: Nagendra Jha
link : https://practice.geeksforgeeks.org/problems/delete-without-head-pointer/1
'''
def deleteNode(curr_node):
# temp = curr_node
curr_node.data = curr_node.next.data
curr_node.next = curr_node.next.next
return
#code here
#{
# 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("test case :"))
for cases in range(t):
n = int(input("input n"))
a = LinkedList() # create a new linked list 'a'.
nodes = list(map(int, input("list of inputs: ").strip().split()))
for x in nodes:
a.append(x)
del_elem = int(input("delete elem"))
to_delete=a.getNode(del_elem)
deleteNode(to_delete)
a.printList()
# } Driver Code Ends