-
Notifications
You must be signed in to change notification settings - Fork 1k
/
Copy pathdelete_node.py
67 lines (53 loc) · 1.43 KB
/
delete_node.py
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
'''
Given head pointer you have to delete the value of the node to delete
'''
class ListNode():
#Node Class
def __init__(self,value=None):
self.data = value
self.next = None
# function for creating linked list
def create_LinkedList(head,val):
if(head.next!=None):
temp = head.next
while(temp.next!=None):
temp = temp.next
newnode = ListNode(val)
newnode.next = None
temp.next = newnode
else:
newnode = ListNode(val)
newnode.next = None
head.next = newnode
#function for displaying linked list
def print_linkedlist(head):
temp = head.next
while(temp!=None):
print(temp.data,end =' ')
temp = temp.next
print()
#function to delete a node from linked list
def delete_node(node):
if node.next is not None:
node.data, node.next = node.next.data, node.next.next
if __name__ == '__main__':
head = ListNode()
n = int(input("Enter total no of elemets in linked list :"))
for i in range(n):
create_LinkedList(head,int(input()))
print_linkedlist(head)
delete_node(head.next.next)
print_linkedlist(head)
# OUPUT :
# Enter total no of elemets in linked list :5
# 3
# 4
# 5
# 6
# 7
# 3 4 5 6 7
# 3 5 6 7
'''
Time complexity : O(N)
Space complexity :O(1)
'''