-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDeletion and Reverse in Circular Linked List.py
102 lines (81 loc) · 2.21 KB
/
Deletion and Reverse in Circular Linked List.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
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
#User function Template for python3
'''
class Node:
def __init__(self, data):
self.data = data
self.next = None
'''
class Solution:
# Function to reverse a circular linked list
def reverse(self, head):
if head is None or head.next == head:
return head
prev = None
curr = head
next = None
while True:
next = curr.next
curr.next = prev
prev = curr
curr = next
if curr == head:
break
head.next = prev
return prev
# Function to delete a node from the circular linked list
def deleteNode(self, head, key):
if head is None:
return None
# Case 1: Deleting the head node
if head.data == key:
if head.next == head:
return None
tail = head
while tail.next != head:
tail = tail.next
new_head = head.next
tail.next = new_head
return new_head
# Case 2: Deleting a non-head node
prev = head
cur = head.next
while cur != head:
if cur.data == key:
prev.next = cur.next
return head
prev = cur
cur = cur.next
return head
#{
# Driver Code Starts
class Node:
def __init__(self, data):
self.data = data
self.next = None
def printList(head):
if head is None:
print("empty")
return
temp = head
while True:
print(temp.data, end=" ")
temp = temp.next
if temp == head:
break
print()
if __name__ == "__main__":
t = int(input())
for _ in range(t):
arr = list(map(int, input().split()))
key = int(input())
head = Node(arr[0])
tail = head
for i in range(1, len(arr)):
tail.next = Node(arr[i])
tail = tail.next
tail.next = head # Make the list circular
ob = Solution()
head = ob.deleteNode(head, key)
head = ob.reverse(head)
printList(head)
# } Driver Code Ends