모든 챌린지
쉬움 0명 해결 정답률 0%

Linked List Operations

Simulate a linked list: add at either end, remove from the front or by value, and reverse it.

배우게 될 내용

  • Add and remove nodes at both ends
  • Remove the first node with a given value
  • Reverse the order of a list

문제

번역본 보기

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

예시

예시 1
입력:
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].

예시 2
입력:
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에 맞게 수정되었습니다. 위의 설명과 제한 조건을 따르세요.

다른 사람의 풀이 보기

커뮤니티 솔루션

아직 공개된 풀이가 없습니다. 문제를 풀고 첫 풀이를 공유하세요.