-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSwap-Nodes-InPairs
More file actions
61 lines (42 loc) · 1.13 KB
/
Swap-Nodes-InPairs
File metadata and controls
61 lines (42 loc) · 1.13 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
class ListNode:
def __init__(self, val=0):
self.val = val
self.next = None
# Function to swap nodes in pairs
def swapPairs(head):
dummy = ListNode(0)
dummy.next = head
prev = dummy
while prev.next and prev.next.next:
first = prev.next
second = prev.next.next
# Swapping
first.next = second.next
second.next = first
prev.next = second
# Move pointer forward
prev = first
return dummy.next
# Helper function to create linked list
def createList(arr):
if not arr:
return None
head = ListNode(arr[0])
current = head
for val in arr[1:]:
current.next = ListNode(val)
current = current.next
return head
# Helper function to print linked list
def printList(head):
result = []
while head:
result.append(head.val)
head = head.next
print(result)
# User Input
arr = list(map(int, input("Enter linked list elements: ").split()))
head = createList(arr)
new_head = swapPairs(head)
print("After swapping:")
printList(new_head)