How to Swap List Elements Without Using Key in Python

In this tutorial, we will learn how to program "How to Swap List Elements Without Using a Key in Python." The objective is to swap list elements without using keys in a linked list. This tutorial will guide you step by step through the process of swapping list elements without using keys. By the end of this tutorial, you will have a solid understanding of how to implement this task effectively in Python, helping you strengthen your problem-solving abilities and improve your coding skills.

This topic is straightforward and easy to understand. Simply follow the instructions provided, and you will complete it with ease. The program will guide you step by step through the process of swapping list elements without using a key in a linked list. So, let's dive into the coding process!

Getting Started:

First you will have to download & install the Python IDLE's, here's the link for the Integrated Development And Learning Environment for Python https://www.python.org/downloads/.

Creating Main Function

This is the main function of the application. The following code will display a simple GUI in terminal console that will display program. To do this, simply copy and paste these blocks of code into the IDLE text editor.
  1. class Node:
  2.     def __init__(self, data):
  3.         self.data = data
  4.         self.next = None
  5.  
  6.  
  7. class LinkedList:
  8.     def __init__(self):
  9.         self.head = None
  10.         self.last_node = None
  11.  
  12.     def append(self, data):
  13.         if self.last_node is None:
  14.             self.head = Node(data)
  15.             self.last_node = self.head
  16.         else:
  17.             self.last_node.next = Node(data)
  18.             self.last_node = self.last_node.next
  19.  
  20.     def display(self):
  21.         current = self.head
  22.         while current:
  23.             print(current.data, end=' ')
  24.             current = current.next
  25.         print()
  26.  
  27.     def get_node(self, index):
  28.         current = self.head
  29.         for _ in range(index):
  30.             if current is None:
  31.                 return None
  32.             current = current.next
  33.         return current
  34.  
  35.     def get_prev_node(self, ref_node):
  36.         current = self.head
  37.         while current and current.next != ref_node:
  38.             current = current.next
  39.         return current
  40.  
  41.  
  42. def interchange(llist, n, m):
  43.     if n == m:
  44.         return
  45.  
  46.     node1 = llist.get_node(n)
  47.     node2 = llist.get_node(m)
  48.  
  49.     if node1 is None or node2 is None:
  50.         print("Invalid indices.")
  51.         return
  52.  
  53.     prev_node1 = llist.get_prev_node(node1)
  54.     prev_node2 = llist.get_prev_node(node2)
  55.  
  56.     # Update previous nodes
  57.     if prev_node1:
  58.         prev_node1.next = node2
  59.     else:
  60.         llist.head = node2
  61.  
  62.     if prev_node2:
  63.         prev_node2.next = node1
  64.     else:
  65.         llist.head = node1
  66.  
  67.     # Swap next pointers
  68.     node1.next, node2.next = node2.next, node1.next
  69.  
  70.  
  71. while True:
  72.     print("\n============= Swap List Elements Without Using Key =============\n")
  73.  
  74.     a_llist = LinkedList()
  75.  
  76.     data_list = input(
  77.         "Please enter the elements in the linked list (space-separated): "
  78.     ).split()
  79.  
  80.     for data in data_list:
  81.         a_llist.append(int(data))
  82.  
  83.     ans = input(
  84.         "Enter the two indices of elements to swap (space-separated): "
  85.     ).split()
  86.  
  87.     n = int(ans[0])
  88.     m = int(ans[1])
  89.  
  90.     interchange(a_llist, n, m)
  91.  
  92.     print("The new list:")
  93.     a_llist.display()
  94.  
  95.     # Ask user if they want to try again
  96.     opt = input("\nDo you want to try again? (yes/no): ").strip().lower()
  97.     if opt == "no":
  98.         print("Exiting program...")
  99.         break
  100.     elif opt != "yes":
  101.         print("Invalid choice. Exiting program...")
  102.         break

This program demonstrates how to swap two elements in a singly linked list without using their data values (keys). It builds a linked list from user input and allows the user to specify two indices representing the positions of the nodes to be swapped. The program locates the target nodes and their previous nodes, then updates the `next` pointers to interchange their positions safely, including handling cases where one of the nodes is the head. After performing the swap, the updated linked list is displayed, and the program provides an option to repeat the process or exit.

Output:

There you have it we successfully created How to Swap List Elements Without Using Key in Python. I hope that this simple tutorial help you to what you are looking for. For more updates and tutorials just kindly visit this site. Enjoy Coding!

More Tutorials for Python Language

Python Tutorials