Swap two data in Linked List without swapping node

 In this program we will see how to swap two node data without swapping the actual node.


class Node:
    def __init__(self,data):
        self.data = data
        self.next = None

class LinkedList:
    def __init__(self):
        self.head = None

    def display(self):
        temp = self.head
        while temp!=None:
            print(temp.data,end="=>")
            temp = temp.next
    def length(self):
        temp = self.head
        count = 0
        while temp!=None:
            count = count+1
            temp = temp.next
        return count
    def swap(self,index1,index2):
        if index2>self.length() or index2<1 or index1>self.length() or index1<1:
            print("\nEnter a valid index")
        else: 
            temp1 = self.getAddress(index1)
            temp2 = self.getAddress(index2)
            temp_data = 0
            print(f"\nvalue at {temp1} before swap is {temp1.data}")
            temp_data = temp1.data
            temp1.data = temp2.data
            temp2.data = temp_data
            print(f"\nvalue at {temp1} after swap is {temp1.data}")

    def getAddress(self,index):
        temp = self.head
        count = 1
        while count!=index:
            temp = temp.next
            count = count+1
        return temp
if __name__=="__main__":
    llist = LinkedList()
    first = Node(10)
    second = Node(20)
    third = Node(30)
    fourth = Node(40)
    fifth = Node(50)
    llist.head = first
    first.next = second
    second.next = third
    third.next = fourth
    fourth.next = fifth
    llist.display()
    llist.swap(2,3)
    print("\nAfter Swap")
    llist.display()
    

No comments:

Post a Comment