by CodeJin19
1 min read

Categories

Tags

오늘의 문제는 “10828번 스택”.

대표적인 자료구조인 스택을 구현하는 것이다.

노드를 직접 구현해도 되지만, 간단히 10000자리 1차원 배열로 풀었다.

#include <iostream>

using namespace std;

int main()
{
	int n, x;
	int idx = 0;
	int stck[10010]; //스택
	char arr[10]; //명령어

	cin >> n;

	for (int itr = 0; itr < n; itr++)
	{
		cin >> arr; //명령어 입력

		switch (arr[0])
		{
		case 'p':
			if (arr[1] == 'u')  //push
			{
				cin >> stck[idx];
				idx++;
			}
			else                //pull
			{
				if (idx == 0)
				{
					cout << -1 << "\n";
				}
				else
				{
					cout << stck[idx - 1] << "\n";
					idx--;
				}
			}
			break;
		case 's':             //size
			cout << idx << "\n";
			break;
		case 'e':             //empty
			if (idx == 0)
			{
				cout << "1\n";
			}
			else
			{
				cout << "0\n";
			}
			break;
		case 't':             //top
			cout << stck[idx - 1] << "\n";
			break;
		}
	}

	return 0;
}

간단한 문제라 당연히 맞을 거라고 생각했는데

이번에도 문제 조건을 꼼꼼히 읽지 않아서 틀렸다.

top: 스택의 가장 위에 있는 정수를 출력한다. 만약 스택에 들어있는 정수가 없는 경우에는 -1을 출력한다.

에서 스택이 비어있는 경우를 검사하지 않은 것이다.

#include <iostream>

using namespace std;

int main()
{
	int n, x;
	int idx = 0;
	int stck[10010]; //스택
	char arr[10]; //명령어

	cin >> n;

	for (int itr = 0; itr < n; itr++)
	{
		cin >> arr; //명령어 입력

		switch (arr[0])
		{
		case 'p':
			if (arr[1] == 'u')  //push
			{
				cin >> stck[idx];
				idx++;
			}
			else                //pull
			{
				if (idx == 0)
				{
					cout << -1 << "\n";
				}
				else
				{
					cout << stck[idx - 1] << "\n";
					idx--;
				}
			}
			break;
		case 's':             //size
			cout << idx << "\n";
			break;
		case 'e':             //empty
			if (idx == 0)
			{
				cout << "1\n";
			}
			else
			{
				cout << "0\n";
			}
			break;
		case 't':             //top
			if (idx == 0)
			{
				cout << -1 << "\n";
			}
			else
			{
				cout << stck[idx - 1] << "\n";
			}
			break;
		}
	}

	return 0;
}