-
Notifications
You must be signed in to change notification settings - Fork 1
/
Pairwise_swap_elements_of_a_linked_list.py
82 lines (69 loc) · 1.95 KB
/
Pairwise_swap_elements_of_a_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
class Solution:
def pairWiseSwap(self, head):
firstHead = head
if(head.next == None):
return head
secondHead = head.next
resultHead = secondHead
while(secondHead != None and secondHead.next != None):
tempHead = secondHead.next
secondHead.next = firstHead
if(tempHead.next == None):
firstHead.next = tempHead
else:
firstHead.next = tempHead.next
firstHead = tempHead
secondHead = tempHead.next
if(secondHead):
secondHead.next = firstHead
firstHead.next = None
return resultHead
#{
# Driver Code Starts
#Initial Template for Python 3
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
self.tail = None
def insert(self,val):
if self.head is None:
self.head = Node(val)
self.tail = self.head
else:
self.tail.next = Node(val)
self.tail = self.tail.next
def printList(n):
while n:
print(n.data, end=' ')
n = n.next
print()
if __name__=="__main__":
for _ in range(int(input())):
n = int(input())
arr = [int(x) for x in input().split()]
lis = LinkedList()
for i in arr:
lis.insert(i)
dict1 = {}
temp = lis.head
while temp:
dict1[temp] = temp.data
temp = temp.next
failure = LinkedList()
failure.insert(-1)
head = Solution().pairWiseSwap(lis.head)
temp = head
f = 0
while temp:
if dict1[temp] != temp.data:
f = 1;
temp = temp.next
if f:
printList(failure)
else:
printList(head)
# } Driver Code Ends