Program to swap nodes in a linked list in Python

Swapping the kth node from the start with the kth node from the end in a linked list is a common problem. We need to locate both nodes and swap their values while maintaining the list structure.

Problem Understanding

Given a linked list and a value k, we swap the kth node from the beginning with the kth node from the end. For example, if we have nodes [1,5,6,7,1,6,3,9,12] and k=3, the 3rd node from start (6) swaps with the 3rd node from end (3).

Algorithm Steps

The solution follows these steps ?

  • Find the kth node from the start by traversing k-1 positions
  • Find the kth node from the end using two pointers technique
  • Swap the values of both nodes
  • Return the modified list

Implementation

Here's the complete implementation with helper functions ?

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

def make_list(elements):
    if not elements:
        return None
    head = ListNode(elements[0])
    current = head
    for element in elements[1:]:
        current.next = ListNode(element)
        current = current.next
    return head

def print_list(head):
    result = []
    current = head
    while current:
        result.append(current.val)
        current = current.next
    print(result)

def swap_nodes(head, k):
    # Find kth node from start
    temp = head
    for i in range(k - 1):
        temp = temp.next
    first_node = temp
    
    # Find kth node from end using two pointers
    second_node = head
    while temp.next:
        second_node = second_node.next
        temp = temp.next
    
    # Swap values
    first_node.val, second_node.val = second_node.val, first_node.val
    
    return head

# Test the solution
linked_list = [1, 5, 6, 7, 1, 6, 3, 9, 12]
k = 3

head = make_list(linked_list)
print("Original list:")
print_list(head)

result_head = swap_nodes(head, k)
print(f"After swapping {k}th nodes:")
print_list(result_head)
Original list:
[1, 5, 6, 7, 1, 6, 3, 9, 12]
After swapping 3th nodes:
[1, 5, 3, 7, 1, 6, 6, 9, 12]

How It Works

The algorithm uses a two-pointer technique ?

  1. First pointer: Moves k-1 steps to reach the kth node from start
  2. Second pointer: Starts from head and moves along with the first pointer until the first pointer reaches the end
  3. When the first pointer reaches the end, the second pointer will be at the kth node from end
  4. We swap the values of both nodes

Time and Space Complexity

Aspect Complexity Explanation
Time O(n) Single pass through the list
Space O(1) Only using pointer variables

Conclusion

This solution efficiently swaps the kth nodes from start and end in O(n) time using a two-pointer technique. The key insight is moving both pointers simultaneously to find the kth node from the end without calculating the total length.

Updated on: 2026-03-26T14:25:03+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements