โจทย์
A linked list stores values in nodes that point to the next node, so adding or removing at the front is cheap. Simulate one that starts empty.
Process the operations in order:
push_front x: add x at the front.push_back x: add x at the back.pop_front: remove the first value (ignored when the list is empty).remove x: remove the first node whose value is x, if there is one.reverse: reverse the order of the nodes.
Implement linked_list_operations(operations).
Input
operations: The operations.
Output
Return the values in the list from front to back.
เงื่อนไข
0 ≤ number of operations ≤ 10,000
−10^9 ≤ x ≤ 10^9
ตัวอย่าง
อินพุต:
operations = ["push_back 2", "push_front 1", "push_back 3", "reverse"]
ผลลัพธ์ที่คาดหวัง:
expected = [3, 2, 1]
อินพุต:
std::vector<std::string> operations = {"push_back 2", "push_front 1", "push_back 3", "reverse"};
ผลลัพธ์ที่คาดหวัง:
std::vector<long long> expected = {3, 2, 1};
อินพุต:
string[] operations = new string[] {"push_back 2", "push_front 1", "push_back 3", "reverse"};
ผลลัพธ์ที่คาดหวัง:
long[] expected = new long[] {3, 2, 1};
คำอธิบาย
The list grows to 1 → 2 → 3, and reversing it gives [3, 2, 1].
อินพุต:
operations = ["push_back 5", "push_back 7", "push_back 5", "remove 5", "pop_front"]
ผลลัพธ์ที่คาดหวัง:
expected = [5]
อินพุต:
std::vector<std::string> operations = {"push_back 5", "push_back 7", "push_back 5", "remove 5", "pop_front"};
ผลลัพธ์ที่คาดหวัง:
std::vector<long long> expected = {5};
อินพุต:
string[] operations = new string[] {"push_back 5", "push_back 7", "push_back 5", "remove 5", "pop_front"};
ผลลัพธ์ที่คาดหวัง:
long[] expected = new long[] {5};
คำอธิบาย
remove takes out only the first 5, leaving 7 → 5; pop_front then removes 7: [5].
แนวทางการแก้
ลองทำเองก่อน แล้วค่อยเปิดคำใบ้ทีละข้อ
คำใบ้ 1
A list type with cheap front and back inserts (std::list, LinkedList<T>, deque) does most of the work.
คำใบ้ 2
remove deletes only the first match, and pop_front on an empty list does nothing.
คำใบ้ 3
Reversing changes which end is the front for later pushes and pops.
ความซับซ้อนที่คาดหวัง
O(n²) time, O(n) extra space
แหล่งอ้างอิง
โจทย์นี้ปรับให้เหมาะกับ CodeUtility กรุณาทำตามคำชี้แจงและข้อจำกัดด้านบน