Python Program For Swapping Nodes In A Linked List Without Swapping Data

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 listclass 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 codellist = LinkedList()Â
# The constructed linked list is:# 1->2->3->4->5->6->7llist.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 classclass 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 Listdef 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 codestart = NoneÂ
# The constructed linked list is:# 1.2.3.4.5.6.7start = 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!
You’ll access excellent video content by our CEO, Sandeep Jain, tackle common interview questions, and engage in real-time coding contests covering various DSA topics. We’re here to prepare you thoroughly for online assessments and interviews.
Ready to dive in? Explore our free demo content and join our DSA course, trusted by over 100,000zambiatek! Whether it’s DSA in C++, Java, Python, or JavaScript we’ve got you covered. Let’s embark on this exciting journey together!



