Python Program For Swapping Nodes In A Linked List Without Swapping Data
Last Updated :
30 Mar, 2022
Given a linked list and two keys in it, swap nodes for two given keys. Nodes should be swapped by changing links. Swapping data of nodes may be expensive in many situations when data contains many fields.
It may be assumed that all keys in the linked list are distinct.
Examples:
Input : 10->15->12->13->20->14, x = 12, y = 20
Output: 10->15->20->13->12->14
Input : 10->15->12->13->20->14, x = 10, y = 20
Output: 20->15->12->13->10->14
Input : 10->15->12->13->20->14, x = 12, y = 13
Output: 10->15->13->12->20->14
This may look a simple problem, but is an interesting question as it has the following cases to be handled.
- x and y may or may not be adjacent.
- Either x or y may be a head node.
- Either x or y may be the last node.
- x and/or y may not be present in the linked list.
How to write a clean working code that handles all the above possibilities.
The idea is to first search x and y in the given linked list. If any of them is not present, then return. While searching for x and y, keep track of current and previous pointers. First change next of previous pointers, then change next of current pointers.
Below is the implementation of the above approach.
Python
# Python program to swap two given nodes
# of a linked list
class LinkedList(object):
def __init__(self):
self.head = None
# Head of list
class Node(object):
def __init__(self, d):
self.data = d
self.next = None
# Function to swap Nodes x and y
# in a linked list by changing links
def swapNodes(self, x, y):
# Nothing to do if x and y are
# the same
if x == y:
return
# Search for x (keep track of
# prevX and CurrX)
prevX = None
currX = self.head
while currX != None and currX.data != x:
prevX = currX
currX = currX.next
# Search for y (keep track of
# prevY and currY)
prevY = None
currY = self.head
while currY != None and currY.data != y:
prevY = currY
currY = currY.next
# If either x or y is not present,
# nothing to do
if currX == None or currY == None:
return
# If x is not head of linked list
if prevX != None:
prevX.next = currY
else: # make y the new head
self.head = currY
# If y is not head of linked list
if prevY != None:
prevY.next = currX
else:
# make x the new head
self.head = currX
# Swap next pointers
temp = currX.next
currX.next = currY.next
currY.next = temp
# Function to add Node at beginning
# of list.
def push(self, new_data):
# 1. alloc the Node and put the data
new_Node = self.Node(new_data)
# 2. Make next of new Node as head
new_Node.next = self.head
# 3. Move the head to point to new Node
self.head = new_Node
# This function prints contents of
# linked list starting from the given Node
def printList(self):
tNode = self.head
while tNode != None:
print tNode.data,
tNode = tNode.next
# Driver code
llist = LinkedList()
# The constructed linked list is:
# 1->2->3->4->5->6->7
llist.push(7)
llist.push(6)
llist.push(5)
llist.push(4)
llist.push(3)
llist.push(2)
llist.push(1)
print "Linked list before calling swapNodes() "
llist.printList()
llist.swapNodes(4, 3)
print "
Linked list after calling swapNodes() "
llist.printList()
# This code is contributed by BHAVYA JAIN
Output:
Linked list before calling swapNodes() 1 2 3 4 5 6 7
Linked list after calling swapNodes() 1 2 4 3 5 6 7
Time Complexity: O(n)
Auxiliary Space: O(1)
Optimizations: The above code can be optimized to search x and y in single traversal. Two loops are used to keep program simple.
Simpler approach:
Python
# Python3 program to swap two given
# nodes of a linked list
# A linked list node class
class Node:
# constructor
def __init__(self, val = None,
next1 = None):
self.data = val
self.next = next1
# Print list from this
# to last till None
def printList(self):
node = self
while (node != None):
print(node.data, end = " ")
node = node.next
print(" ")
# Function to add a node
# at the beginning of List
def push(head_ref, new_data):
# Allocate node
(head_ref) = Node(new_data, head_ref)
return head_ref
def swapNodes(head_ref, x, y):
head = head_ref
# Nothing to do if x and y are same
if (x == y):
return None
a = None
b = None
# Search for x and y in the linked list
# and store their pointer in a and b
while (head_ref.next != None):
if ((head_ref.next).data == x):
a = head_ref
elif ((head_ref.next).data == y):
b = head_ref
head_ref = ((head_ref).next)
# If we have found both a and b
# in the linked list swap current
# pointer and next pointer of these
if (a != None and b != None):
temp = a.next
a.next = b.next
b.next = temp
temp = a.next.next
a.next.next = b.next.next
b.next.next = temp
return head
# Driver code
start = None
# The constructed linked list is:
# 1.2.3.4.5.6.7
start = push(start, 7)
start = push(start, 6)
start = push(start, 5)
start = push(start, 4)
start = push(start, 3)
start = push(start, 2)
start = push(start, 1)
print("Linked list before calling swapNodes() ")
start.printList()
start = swapNodes(start, 6, 1)
print("Linked list after calling swapNodes() ")
start.printList()
# This code is contributed by Arnab Kundu
Output:
Linked list before calling swapNodes() 1 2 3 4 5 6 7
Linked list after calling swapNodes() 6 2 3 4 5 1 7
Time Complexity: O(n)
Auxiliary Space: O(1)
Please refer complete article on Swap nodes in a linked list without swapping data for more details!
Similar Reads
Python Program For Reversing Alternate K Nodes In A Singly Linked List
Given a linked list, write a function to reverse every alternate k nodes (where k is an input to the function) in an efficient way. Give the complexity of your algorithm. Example: Inputs: 1->2->3->4->5->6->7->8->9->NULL and k = 3 Output: 3->2->1->4->5->6-
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 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 Deleting a Node in a Linked List
We have discussed Linked List Introduction and Linked List Insertion in previous posts on a singly linked list.Let us formulate the problem statement to understand the deletion process. Given a 'key', delete the first occurrence of this key in the linked list. Iterative Method:To delete a node from
3 min read
Python Program For Printing Reverse Of A Linked List Without Actually Reversing
Given a linked list, print reverse of it using a recursive function. For example, if the given linked list is 1->2->3->4, then output should be 4->3->2->1.Note that the question is only about printing the reverse. To reverse the list itself see this Difficulty Level: Rookie Algorit
2 min read
Python Program For Swapping Kth Node From Beginning With Kth Node From End In A Linked List
Given a singly linked list, swap kth node from beginning with kth node from end. Swapping of data is not allowed, only pointers should be changed. This requirement may be logical in many situations where the linked list data part is huge (For example student details line Name, RollNo, Address, ..etc
5 min read
Python Program For Searching An Element In A Linked List
Write a function that searches a given key 'x' in a given singly linked list. The function should return true if x is present in linked list and false otherwise. bool search(Node *head, int x) For example, if the key to be searched is 15 and linked list is 14->21->11->30->10, then functi
4 min read
Python Program For Cloning A Linked List With Next And Random Pointer In O(1) Space
Given a linked list having two pointers in each node. The first one points to the next node of the list, however, the other pointer is random and can point to any node of the list. Write a program that clones the given list in O(1) space, i.e., without any extra space. Examples: Input : Head of the
4 min read
Python Program For Inserting A Node In A Linked List
We have introduced Linked Lists in the previous post. We also created a simple linked list with 3 nodes and discussed linked list traversal.All programs discussed in this post consider the following representations of linked list. Python # Node class class Node: # Function to initialize the # node o
7 min read
Python Program For Insertion Sort In A Singly Linked List
We have discussed Insertion Sort for arrays. In this article we are going to discuss Insertion Sort for linked list. Below is a simple insertion sort algorithm for a linked list. 1) Create an empty sorted (or result) list. 2) Traverse the given list, do following for every node. ......a) Insert curr
5 min read