Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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 ?
- First pointer: Moves k-1 steps to reach the kth node from start
- Second pointer: Starts from head and moves along with the first pointer until the first pointer reaches the end
- When the first pointer reaches the end, the second pointer will be at the kth node from end
- 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.
