
Data Structures and Algorithms Interview
20 of 20 Completed
Introduction to Linked Lists
Linked List Operations
Assessment 1: Singly Linked Lists
Assessment 2: Pop Tail!
Linked Lists VS. Arrays
Assessment 3: Cyclic Detection
Assessment 4: Swapping Nodes
Assessment 4: Swapping Nodes
Difficulty: HARD
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:
**next = None**
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)
100%
CompletedYou have completed all sections on this learning path.