-
Notifications
You must be signed in to change notification settings - Fork 1
/
Reverse_alternate_nodes_in_Link_List.py
67 lines (55 loc) · 1.63 KB
/
Reverse_alternate_nodes_in_Link_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
class Solution:
def rearrange(self, head):
if not head or not head.next or not head.next.next: return head
first, second, altlast= head, head.next, head.next
while second and second.next:
first.next = second.next
second.next = second.next.next
first = first.next
second = second.next
prev = None
curr = altlast
while curr:
nxt =curr.next
curr.next = prev
prev, curr = curr, nxt
altlast = prev
first.next = altlast
return head
#{
# Driver Code Starts
# Node Class
class Node:
# Constructor to initialize the node object
def __init__(self, data):
self.data = data
self.next = None
# Linked list class contains node object
class LinkedList:
# Constructor to initialize head
def __init__(self):
self.head = None
# Function to insert a new node at the beginning
def push(self, new_data):
new_node = Node(new_data)
new_node.next = self.head
self.head = new_node
def printList(self):
temp = self.head
while (temp):
print(temp.data, end=" ")
temp = temp.next
print()
# Code execution starts here
if __name__ == '__main__':
t = int(input())
while (t > 0):
llist = LinkedList()
n = int(input())
values = list(map(int, input().strip().split()))
for i in reversed(values):
llist.push(i)
Solution().rearrange(llist.head)
llist.printList()
t -= 1
# } Driver Code Ends