[Leet Code] Swap Nodes In Paris
Leetcode: https://leetcode.com/problems/swap-nodes-in-pairs/
Given a linked list, swap every two adjacent nodes and return its head.
You may not modify the values in the list’s nodes. Only nodes itself may be changed.
Example 1:
Input: head = [1,2,3,4]
Output: [2,1,4,3]
Example 2:
Input: head = []
Output: []
Example 3:
Input: head = [1]
Output: [1]
Solution:
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def swapPairs(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if head and head.next:
self.helper(head, head.next)
return head
def helper(self, firstNode, secondNode):
tempNode = firstNode.val
firstNode.val = secondNode.val
secondNode.val = tempNode
if secondNode.next != None and secondNode.next.next != None:
return self.helper(secondNode.next, secondNode.next.next)
Explanation:
First we check that the linked list is greater than length 1 by doing if head and head.next
that will ensure we at least have two nodes to swap.
Then we’re calling into the helper
function. In the helper function, we assign the firstNode’s val (head)to a tempNode variable. We then assign the secondNode (head.next) to the tempNode. That means we’ve now switched both the nodes. Then we’re checking that there are more nodes to carry on, and if so, we recursively call self.helper with the secondNode.next and secondNode.next.next values for the firstNode and secondNode respectively.