Today's challenge on Leetcode in based on Linked List. Although it is listed in Medium difficulty level, it is one of the easiest linked list questions asked in interviews.
[24. Swap Nodes in Pairs]
(https://leetcode.com/problems/swap-nodes-in-pairs/)
The questions states:
Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed.)
Approach
Long story short, it asks you to swap the nodes occurring at even positions with their preceding node. Reading this line, you must have already got the inner intuition if you have already practiced Linked List questions in the past.
The solution took me 15 minutes and No, it does not consist of any swapping the actual nodes or altering them. Instead, the better approach is to switch the values of pair nodes which boils down to the basic swapping without third variable. Node swapping will also lead you to the finish line.
Solution:
class Solution(object):
def swapPairs(self, head):
if head == None or head.next == None:
return head
cur = head
temp = cur
cur = cur.next
ctr = 1
while cur:
if ctr % 2 == 1:
temp.val = temp.val + cur.val
cur.val = temp.val - cur.val
temp.val = temp.val - cur.val
temp = cur
cur = cur.next
ctr += 1
return head
Hope you liked the article, in case you want to learn the fundamentals. Do checkout this YouTube Playlist. Code Broski - Mastering Python Fundamentals
Top comments (0)