Pairwise swap elements of a given linked list by changing links -
class Solution(object):
#Iterative Solution
def swapPairs(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if(head is None or head.next is None):
return head
curr = head.next
prev = head
head = curr
while(True):
sec = curr.next
curr.next = prev
if(sec is None or sec.next is None):
prev.next = sec
break
prev.next = sec.next
prev = sec
curr.next = prev
return head
#Recursively Solution
def swapPairs(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head or not head.next:
return head
sec = head.next
head.next = self.swapPairs(sec.next)
sec.next = head
return sec
class Solution(object):
#Iterative Solution
def swapPairs(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if(head is None or head.next is None):
return head
curr = head.next
prev = head
head = curr
while(True):
sec = curr.next
curr.next = prev
if(sec is None or sec.next is None):
prev.next = sec
break
prev.next = sec.next
prev = sec
curr.next = prev
return head
#Recursively Solution
def swapPairs(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head or not head.next:
return head
sec = head.next
head.next = self.swapPairs(sec.next)
sec.next = head
return sec
Reference - http://www.geeksforgeeks.org/pairwise-swap-elements-of-a-given-linked-list-by-changing-links/
Comments