Python Program For Pairwise Swapping Elements Of A Given Linked List By Changing Links
Last Updated :
12 Sep, 2022
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!
Similar Reads
Python Program For Pairwise Swapping Elements Of A Given Linked List Given a singly linked list, write a function to swap elements pairwise. Input: 1->2->3->4->5->6->NULL Output: 2->1->4->3->6->5->NULL Input: 1->2->3->4->5->NULL Output: 2->1->4->3->5->NULL Input: 1->NULL Output: 1->NULL For examp
2 min read
Python Program For Sorting A Linked List Of 0s, 1s And 2s By Changing Links Given a linked list of 0s, 1s and 2s, sort it.Examples: Input: 2->1->2->1->1->2->0->1->0 Output: 0->0->1->1->1->1->2->2->2 The sorted Array is 0, 0, 1, 1, 1, 1, 2, 2, 2. Input: 2->1->0 Output: 0->1->2 The sorted Array is 0, 1, 2Recommended:
3 min read
Python Program For In-Place Merge Two Linked Lists Without Changing Links Of First List Given two sorted singly linked lists having n and m elements each, merge them using constant space. First, n smallest elements in both the lists should become part of the first list and the rest elements should be part of the second list. Sorted order should be maintained. We are not allowed to chan
4 min read
Python Program For Arranging Single Linked List In Alternate Odd and Even Nodes Order Given a singly linked list, rearrange the list so that even and odd nodes are alternate in the list.There are two possible forms of this rearrangement. If the first data is odd, then the second node must be even. The third node must be odd and so on. Notice that another arrangement is possible where
7 min read
Python Program For Deleting A Linked List Node At A Given Position Given a singly linked list and a position, delete a linked list node at the given position. Example: Input: position = 1, Linked List = 8->2->3->1->7 Output: Linked List = 8->3->1->7 Input: position = 0, Linked List = 8->2->3->1->7 Output: Linked List = 2->3->1
3 min read
Python Program For Rearranging A Given Linked List In-Place Given a singly linked list L0 -> L1 -> ⦠-> Ln-1 -> Ln. Rearrange the nodes in the list so that the new formed list is: L0 -> Ln -> L1 -> Ln-1 -> L2 -> Ln-2 ...You are required to do this in place without altering the nodes' values. Examples: Input: 1 -> 2 -> 3 ->
6 min read
Python Program For Alternating Split Of A Given Singly Linked List- Set 1 Write a function AlternatingSplit() that takes one list and divides up its nodes to make two smaller lists 'a' and 'b'. The sublists should be made from alternating elements in the original list. So if the original list is 0->1->0->1->0->1 then one sublist should be 0->0->0 and
3 min read
Python Program For Finding The Middle Element Of A Given Linked List Given a singly linked list, find the middle of the linked list. For example, if the given linked list is 1->2->3->4->5 then the output should be 3. If there are even nodes, then there would be two middle nodes, we need to print the second middle element. For example, if given linked list
4 min read
Python Program For Moving Last Element To Front Of A Given Linked List Write a function that moves the last element to the front in a given Singly Linked List. For example, if the given Linked List is 1->2->3->4->5, then the function should change the list to 5->1->2->3->4. Algorithm: Traverse the list till the last node. Use two pointers: one t
3 min read
Python Program For Deleting A Given Node In Linked List Under Given Constraints Given a Singly Linked List, write a function to delete a given node. Your function must follow following constraints: 1) It must accept a pointer to the start node as the first parameter and node to be deleted as the second parameter i.e., a pointer to head node is not global. 2) It should not retur
3 min read