Bird
Raised Fist0
DSA Rustprogramming~5 mins

Queue Implementation Using Linked List in DSA Rust - Time & Space Complexity

Choose your learning style10 modes available
Time Complexity: Queue Implementation Using Linked List
O(1)
Understanding Time Complexity

We want to understand how fast the queue operations run when using a linked list.

Specifically, how the time to add or remove items changes as the queue grows.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


struct Node {
    value: i32,
    next: Option>,
}

struct Queue {
    front: Option>,
    rear: *mut Node,
}

impl Queue {
    fn enqueue(&mut self, val: i32) {
        let mut new_node = Box::new(Node { value: val, next: None });
        let raw_node: *mut _ = &mut *new_node;
        if self.rear.is_null() {
            self.front = Some(new_node);
            self.rear = raw_node;
        } else {
            unsafe { (*self.rear).next = Some(new_node); }
            self.rear = raw_node;
        }
    }

    fn dequeue(&mut self) -> Option {
        self.front.take().map(|node| {
            self.front = node.next;
            if self.front.is_none() {
                self.rear = std::ptr::null_mut();
            }
            node.value
        })
    }
}
    

This code adds (enqueue) and removes (dequeue) items from a queue using a linked list.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Adding or removing one node at a time.
  • How many times: Each enqueue or dequeue runs once per call, no loops inside.
How Execution Grows With Input

Each operation works the same regardless of queue size.

Input Size (n)Approx. Operations
101 operation per enqueue or dequeue
1001 operation per enqueue or dequeue
10001 operation per enqueue or dequeue

Pattern observation: The time to add or remove does not increase as the queue grows.

Final Time Complexity

Time Complexity: O(1)

This means adding or removing an item takes the same short time no matter how many items are in the queue.

Common Mistake

[X] Wrong: "Enqueue or dequeue takes longer as the queue gets bigger because it has to look through all nodes."

[OK] Correct: The linked list keeps track of the front and rear nodes, so it adds or removes directly without searching.

Interview Connect

Knowing that queue operations run in constant time shows you understand efficient data structures, a key skill in coding interviews.

Self-Check

"What if we did not keep a pointer to the rear node? How would the time complexity of enqueue change?"

Practice

(1/5)
1. What is the main advantage of implementing a Queue using a linked list instead of an array?
easy
A. Simpler to implement than arrays
B. Faster access to elements by index
C. Dynamic size without fixed capacity limit
D. Uses less memory for small queues

Solution

  1. Step 1: Understand queue size behavior

    Arrays have fixed size or require resizing, linked lists grow dynamically.
  2. Step 2: Compare memory and resizing

    Linked lists allocate nodes as needed, so no fixed capacity limit exists.
  3. Final Answer:

    Dynamic size without fixed capacity limit -> Option C
  4. Quick Check:

    Linked list queues grow dynamically = D [OK]
Hint: Linked lists grow dynamically, arrays have fixed size [OK]
Common Mistakes:
  • Thinking linked lists allow fast random access
  • Assuming arrays use less memory always
  • Confusing implementation simplicity
2. Which of the following is the correct Rust syntax to define a node struct for a linked list queue?
easy
A. struct Node { data: i32, next: Option }
B. struct Node { data: i32, next: Node }
C. struct Node { data: i32, next: &Node }
D. struct Node { data: i32, next: Box<Node> }

Solution

  1. Step 1: Understand Rust ownership for linked lists

    Rust requires heap allocation for recursive types using Box and Option for nullable links.
  2. Step 2: Analyze options

    struct Node { data: i32, next: Option } uses Option which is correct for nullable next pointer; others cause infinite size or borrowing issues.
  3. Final Answer:

    struct Node { data: i32, next: Option } -> Option A
  4. Quick Check:

    Use Option for nullable next in Rust [OK]
Hint: Use Option for next pointer in Rust linked list [OK]
Common Mistakes:
  • Using direct Node type causes infinite size error
  • Using references (&Node) without lifetime causes errors
  • Omitting Option for nullable next pointer
3. Given the following Rust code snippet for a queue implemented with a linked list, what will be printed after enqueueing 10, 20 and then dequeueing once?
let mut queue = Queue::new();
queue.enqueue(10);
queue.enqueue(20);
let val = queue.dequeue();
println!("Dequeued: {:?}", val);
queue.print();
medium
A. Dequeued: Some(10) 20 -> null
B. Dequeued: Some(20) 10 -> null
C. Dequeued: None 10 -> 20 -> null
D. Dequeued: Some(10) 10 -> 20 -> null

Solution

  1. Step 1: Trace enqueue operations

    Enqueue 10 adds node with 10, then enqueue 20 adds node with 20 at the end.
  2. Step 2: Trace dequeue operation

    Dequeue removes front node (10), returns Some(10). Remaining queue has 20 only.
  3. Final Answer:

    Dequeued: Some(10) 20 -> null -> Option A
  4. Quick Check:

    First in first out, dequeue returns 10, queue left with 20 [OK]
Hint: Dequeue removes front, so first enqueued is first out [OK]
Common Mistakes:
  • Assuming dequeue removes last element
  • Printing queue before dequeue
  • Confusing Some and None return values
4. Identify the bug in this Rust enqueue method for a linked list queue:
fn enqueue(&mut self, data: i32) {
    let new_node = Box::new(Node { data, next: None });
    if self.tail.is_none() {
        self.head = Some(new_node);
    } else {
        self.tail.as_mut().unwrap().next = Some(new_node);
    }
    self.tail = Some(new_node);
}
medium
A. Not updating head when queue is empty
B. Using Box instead of Rc for nodes
C. Missing return statement in enqueue
D. Assigning new_node to tail after moving it causes use-after-move error

Solution

  1. Step 1: Analyze ownership of new_node

    new_node is moved into head or tail.next, so cannot be moved again.
  2. Step 2: Identify use-after-move error

    Assigning self.tail = Some(new_node) after moving new_node causes compile error.
  3. Final Answer:

    Assigning new_node to tail after moving it causes use-after-move error -> Option D
  4. Quick Check:

    Moving new_node twice causes error [OK]
Hint: Don't move ownership twice; clone or restructure [OK]
Common Mistakes:
  • Ignoring Rust ownership rules
  • Not updating tail pointer correctly
  • Confusing Box and Rc usage
5. You want to implement a method peek for your linked list queue in Rust that returns the front element without removing it. Which approach is correct?
hard
A. Return Option<i32> by cloning data from head node
B. Return Option<&i32> by borrowing data from head node
C. Return i32 directly, panicking if queue is empty
D. Return Option by moving head node

Solution

  1. Step 1: Understand peek method goal

    Peek returns front element without removing it, so no ownership transfer.
  2. Step 2: Choose correct return type

    Borrowing data with Option<&i32> avoids cloning or moving, safe and efficient.
  3. Final Answer:

    Return Option<&i32> by borrowing data from head node -> Option B
  4. Quick Check:

    Peek borrows front data, no ownership change [OK]
Hint: Peek borrows front data, don't move or clone unnecessarily [OK]
Common Mistakes:
  • Moving head node causing queue modification
  • Returning owned data causing unnecessary clone
  • Panicking instead of returning Option
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard