diff --git a/Recursion/python/Swap_Nodes_In_Pairs.py b/Recursion/python/Swap_Nodes_In_Pairs.py new file mode 100644 index 0000000..7ad2878 --- /dev/null +++ b/Recursion/python/Swap_Nodes_In_Pairs.py @@ -0,0 +1,17 @@ +# Given a linked list, swap every two adjacent nodes and return its head. +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next + +def swapPairs(head): + # Base condition for recursive solution + if head is not None: + if head.next is None: + return head + # next element of head will be swapped head + new_head = head.next + # Swapping algorithm: recursion + new_head.next, head.next = head, swapPairs(new_head.next) + return new_head