Open In App

Python Program For Pairwise Swapping Elements Of A Given Linked List By Changing Links

Last Updated : 12 Sep, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Given a singly linked list, write a function to swap elements pairwise. For example, if the linked list is 1->2->3->4->5->6->7 then the function should change it to 2->1->4->3->6->5->7, and if the linked list is 1->2->3->4->5->6 then the function should change it to 2->1->4->3->6->5

This problem has been discussed here. The solution provided there swaps data of nodes. If data contains many fields, there will be many swap operations. So changing links is a better idea in general. Following is the implementation that changes links instead of swapping data. 

Python3




# Python3 program to swap elements of
# linked list by changing links
 
# Linked List Node
class Node:   
    def __init__(self, data):       
        self.data = data
        self.next = None
 
# Create and Handle list
# operations
class LinkedList:
     
    def __init__(self):
         
        # Head of list
        self.head = None
 
    # Add data to list
    def addToList(self, data):       
        newNode = Node(data)
        if self.head is None:
            self.head = newNode
            return
 
        last = self.head
         
        while last.next:
            last = last.next
 
        last.next = newNode
 
    # Function to print nodes
    # in a given linked list
    def __str__(self):       
        linkedListStr = ""
        temp = self.head
         
        while temp:
            linkedListStr = (linkedListStr +
                             str(temp.data) + " ")
            temp = temp.next
             
        return linkedListStr
 
    # Function to pairwise swap elements
    # of a linked list. It returns head of
    # the modified list, so return value
    # of this node must be assigned
    def pairWiseSwap(self):
 
        # If list is empty or with one
        # node
        if (self.head is None or
            self.head.next is None):
            return
 
        # Initialize previous and current
        # pointers
        prevNode = self.head
        currNode = self.head.next
 
        # Change head node
        self.head = currNode
 
        # Traverse the list
        while True:
            nextNode = currNode.next
             
            # Change next of current
            # node to previous node
            currNode.next = prevNode 
 
            # If next node is the last node
            if nextNode.next is None:
                prevNode.next = nextNode
                break
 
            # Change next of previous to
            # next of next
            prevNode.next = nextNode.next
 
            # Update previous and current nodes
            prevNode = nextNode
            currNode = prevNode.next
 
# Driver Code
linkedList = LinkedList()
linkedList.addToList(1)
linkedList.addToList(2)
linkedList.addToList(3)
linkedList.addToList(4)
linkedList.addToList(5)
linkedList.addToList(6)
linkedList.addToList(7)
 
print("Linked list before calling" 
      "pairwiseSwap() ", linkedList)
       
linkedList.pairWiseSwap()
 
print("Linked list after calling "
      "pairwiseSwap() ", linkedList)
# This code is contributed by AmiyaRanjanRout


Output: 

Linked list before calling  pairWiseSwap() 1 2 3 4 5 6 7
Linked list after calling  pairWiseSwap() 2 1 4 3 6 5 7

Time Complexity: The time complexity of the above program is O(n) where n is the number of nodes in a given linked list. The while loop does a traversal of the given linked list.

Auxiliary Space: O(1) because constant space has been used

Following is the recursive implementation of the same approach. We change the first two nodes and recur for the remaining list. Thanks to geek and omer salem for suggesting this method. 

Python3




# Python3 program to pairwise swap
# linked list using recursive method
 
# Linked List Node
class Node:   
    def __init__(self, data):       
        self.data = data
        self.next = None
 
# Create and Handle list
# operations
class LinkedList:   
    def __init__(self):
         
        # Head of list
        self.head = None 
 
    # Add data to list
    def addToList(self, data):       
        newNode = Node(data)
         
        if self.head is None:
            self.head = newNode
            return
 
        last = self.head
         
        while last.next:
            last = last.next
 
        last.next = newNode
 
    # Function to print nodes in
    # a given linked list
    def __str__(self):       
        linkedListStr = ""
        temp = self.head
         
        while temp:
            linkedListStr = (linkedListStr +
                             str(temp.data) + " ")
            temp = temp.next
        return linkedListStr
 
    # Function to pairwise swap elements of
    # a linked list. It returns head of the
    # modified list, so return value
    # of this node must be assigned
    def pairWiseSwap(self, node):
 
        # If list is empty or with one node
        if node is None or node.next is None:
            return node
 
        # Store head of list after
        # 2 nodes
        remaining = node.next.next
 
        # Change head
        newHead = node.next
 
        # Change next to second node
        node.next.next = node
 
        # Recur for remaining list and
        # change next of head
        node.next = self.pairWiseSwap(remaining)
 
        # Return new head of modified list
        return newHead
 
# Driver Code
linkedList = LinkedList()
linkedList.addToList(1)
linkedList.addToList(2)
linkedList.addToList(3)
linkedList.addToList(4)
linkedList.addToList(5)
linkedList.addToList(6)
linkedList.addToList(7)
 
print("Linked list before calling "
      "pairwiseSwap() ", linkedList)
       
linkedList.head = linkedList.pairWiseSwap(
                  linkedList.head)
print("Linked list after calling "
      "pairwiseSwap() ", linkedList)
# This code is contributed by AmiyaRanjanRout


Output: 

Linked list before calling  pairWiseSwap() 1 2 3 4 5 6 7
Linked list after calling  pairWiseSwap() 2 1 4 3 6 5 7

Please refer complete article on Pairwise swap elements of a given linked list by changing links for more details!



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads