问题重述

Problem Statement:

Given a linked list, swap the two nodes present at position i and j. The positions are based on 0-based indexing.

Note: You have to swap the nodes and not just the values.

Example: * linked_list = 3 4 5 2 6 1 9 * positions = 3 4 * output = 3 4 5 6 2 1 9

Explanation: * The node at position 3 has the value 2 * The node at position 4 has the value 6 * Swapping these nodes will result in a final order of nodes of 3 4 5 6 2 1 9

python实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Node:
"""LinkedListNode class to be used for this problem"""
def __init__(self, data):
self.value = data
self.next = None

def swap_nodes(head, left_index, right_index):
i = 0
node = head
left_node = head
left_value = None
right_node = head
right_value = None
while i <= right_index:
if i == left_index:
left_node = node
left_value = node.value
if i == right_index:
right_node = node
right_value = node.value
i += 1
node = node.next
left_node.value = right_value
right_node.value = left_value
return head

测试用例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# helper functions for testing purpose
def create_linked_list(arr):
if len(arr)==0:
return None
head = Node(arr[0])
tail = head
for data in arr[1:]:
tail.next = Node(data)
tail = tail.next
return head

def print_linked_list(head):
while head:
print(head.value, end=" ")
head = head.next
print()

arr = [3, 4, 5, 2, 6, 1, 9]
head = create_linked_list(arr)
left_index = 3
right_index = 4
print_linked_list(swap_nodes(head, left_index, right_index))

arr = [3, 4, 5, 2, 6, 1, 9]
left_index = 2
right_index = 4
head = create_linked_list(arr)
print_linked_list(swap_nodes(head, left_index, right_index))

arr = [3, 4, 5, 2, 6, 1, 9]
left_index = 0
right_index = 1
head = create_linked_list(arr)
print_linked_list(swap_nodes(head, left_index, right_index))