[백준] 10828번 스택 / C++

#문제

백준 10828번 스택

#풀이

#include <iostream>
#include <string>
#include <memory>

using namespace std;

struct Node
{
	int data;
	unique_ptr<Node> prevNode;

	Node(int x) : data(x), prevNode(nullptr) {}
};

class St
{
	unique_ptr<Node> top;
	int size;

public:
	St() : top(nullptr), size(0) {}

	void Push(int x)
	{
		auto newNode = make_unique<Node>(x);

		newNode->prevNode = std::move(top);
		top = move(newNode);
		size++;
	}
	void Pop()
	{
		if (top != nullptr)
		{
			cout << top->data << '\n';
			top = move(top->prevNode);
			size--;
		}
		else
		{
			cout << "-1" << '\n';
		}
	}
	void Size()
	{
		cout << size << '\n';
	}
	void Empty()
	{
		cout << (size == 0 ? '1' : '0') << '\n';
	}
	void Top()
	{
		if (top != nullptr)
		{
			cout << top->data << '\n';
		}
		else
		{
			cout << "-1" << '\n';
		}
	}
};

int main()
{
	ios::sync_with_stdio(false);
	cin.tie(nullptr);

	int n;
	cin >> n;

	auto st = make_unique<St>();

	while (n--)
	{
		string oper;
		cin >> oper;

		if (oper == "push")
		{
			int x;
			cin >> x;

			st->Push(x);
		}
		else if (oper == "pop")
		{
			st->Pop();
		}
		else if (oper == "size")
		{
			st->Size();
		}
		else if (oper == "empty")
		{
			st->Empty();
		}
		else
		{
			st->Top();
		}
	}

	return 0;
}

#정리

문제 목적에 따라 직접 스택을 구현하여 해결. 스마트 포인터를 사용하여 해제를 신경쓰지 않도록 작성했다.




    Enjoy Reading This Article?

    Here are some more articles you might like to read next:

  • [백준] 10866번 덱 / C++
  • [백준] 18258번 큐 2 / C++
  • [백준] 10845번 큐 / C++
  • [백준] 11723번 집합 / C++
  • [백준] 25206번 너의 평점은 / C++