U

51. Singly Linked List Operations (Head, Tail, Traverse)

Easy

Problem Description

Implement a singly linked list supporting:

  • •head x: Insert xx at head
  • •tail x: Insert xx at tail
  • •print: Print all elements space-separated, or EMPTY

Input Format

  • •Line 1: An integer QQ.
  • •Next QQ lines: Operation commands.

Output Format

For each print, output elements or EMPTY.

Example 1:
Input:
4
head 10
tail 20
head 5
print
Output:
5 10 20
Explanation: Head 10, tail 20, head 5 produces 5 10 20.
Example 2:
Input:
2
head 1
print
Output:
1
Explanation: Single element list.
Example 3:
Input:
1
print
Output:
EMPTY
Explanation: Empty list.
Constraints:
  • Standard integer bounds: 32-bit signed integer or input range [1, 10^5].
  • Time complexity target: O(N) or O(N log N) where applicable.
  • Auxiliary space target: O(1) or minimal auxiliary memory.
Follow up:Can this algorithm be adapted to an online streaming setting where the entire input cannot be held in memory simultaneously?
1,180 Online