Iteration in O(n) time and O(1) space:
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def swapPairs(self, head): """ :type head: ListNode :rtype: ListNode """ if head is None: return None dummy = ListNode(0) dummy.next = head cur = dummy while cur.next and cur.next.next: first, second = cur.next, cur.next.next first.next = second.next cur.next = second second.next = first cur = first return dummy.next
Recursion in O(n) time and space:
This solution is taken from here.
class Solution(object): def swapPairs(self, head): """ :type head: ListNode :rtype: ListNode """ if head is None or head.next is None: return head n = head.next head.next = self.swapPairs(head.next.next) n.next = head return n
python iterative and recursive solutions sharing
Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.