Swapping Nodes

Start Timer

0:00:00

Given the head of a singly linked list represented as a ListNode, and two zero-indexed positions x and y, write a function swap_node which swaps the positions of nodes x and y and returns the new head. Note that you cannot simply swap the values of these nodes, as these nodes do not have values. Instead, you must swap these two using pointer manipulation (i.e., modifying the next references of the involved nodes inside the list).

A ListNode is defined as:

class ListNode:
    def __init__(self, label=None, next=None):
        self.label = label  # only names the node, like a memory location
        self.next = next

Example:

Input:

linked_list = ListNode(0x01) -> ListNode(0x02) -> ListNode(0x03) 
# Here, imagine that '0x0_' refer to their memory locations.
head = 0x01
x = 1
y = 2

Output:

def swap_node(head, x, y) ->  ListNode(0x01)  -> ListNode(0x03) -> ListNode(0x02)
.
.
.
.
.


Comments

Loading comments