알고리즘/백준풀이2. 스택
(1) [C++,Java, Python] 백준 No.10828 : 스택(기본구현)
Storage Gonie
2019. 4. 22. 17:02
반응형
문제
풀이
# C++(직접구현)
#include <iostream>
using namespace std;
struct Stack{
// 필수적으로 필요한 멤버변수
int data[1000]; // 데이터 저장 -> 문자열을 저장하고 싶으면 string 타입으로 변경한 뒤, 함수들의 return 형을 조금 수정해주면 된다.
int size; // 여러 연산을 위해 필요함
// 생성자 : 멤버변수의 초기화를 담당한다. 이것이 존재하지 않으면 경고가 뜸.
Stack()
{
size = 0;
}
void push(int n)
{
data[size] = n;
size += 1;
}
int pop()
{
if (size == 0)
return -1;
else{
size -= 1; // pop 할 때 데이터를 따로 삭제해주는 작업은 없다.(다시 push시 덮어쓰면 되므로)
return data[size];
}
}
bool empty()
{
return (size == 0) ? true : false;
}
int top()
{
return (size == 0) ? -1 : data[size-1];
}
};
int main(void)
{
ios::sync_with_stdio(false);
int N;
Stack st; // 구조체 타입의 변수 생성
cin >> N;
while(N--){
string cmd;
cin >> cmd;
if (cmd == "push")
{
int a;
cin >> a;
st.push(a);
}
else if (cmd == "pop")
cout << st.pop() << endl;
else if (cmd == "size")
cout << st.size << endl;
else if (cmd == "empty")
cout << st.empty() << endl;
else if (cmd == "top")
cout << st.top() << endl;
}
}
# C++(STL 사용)
- STL의 stack 이용
- 주의!
STL의 pop() 메소드는 데이터를 빼버리는 역할로만 사용해야지 반환받은걸 사용하려 하려는 목적으로 사용하면 안된다.
pop했을 때 나오는 데이터를 얻고자 한다면 pop() 메소드 호출 전에 top() 메소드로 데이터를 얻는 방식으로 해야 한다.
#include <iostream>
#include <stack>
using namespace std;
int main()
{
stack<int> st; // 숫자를 저장할 수 있는 스택
while(1)
{
string cmd;
cin >> cmd;
if(cmd == "push")
{
int num;
cin >> num;
st.push(num);
}
else if(cmd == "pop")
{
cout << (st.empty() ? -1 : st.top()) << endl;
if (!st.empty())
st.pop();
}
else if(cmd == "top")
cout << (st.empty() ? -1 : st.top()) << endl;
else if(cmd == "size")
cout << st.size() << endl;
else if(cmd == "empty")
cout << st.empty() << endl;
}
}
# Java
- java.util.Stack 이용
import java.util.*;
public class Main {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
sc.nextLine(); // 정수 뒤에 \n이 있어서 필요합니다
Stack<Integer> stack = new Stack<Integer>();
for (int k=0; k<n; k++) {
String line = sc.nextLine();
String[] s = line.split(" ");
String cmd = s[0];
if (cmd.equals("push"))
{
int num = Integer.parseInt(s[1]);
stack.push(num);
}
else if (cmd.equals("top"))
{
if (stack.empty())
System.out.println("-1");
else
System.out.println(stack.peek());
}
else if (cmd.equals("size"))
System.out.println(stack.size());
else if (cmd.equals("empty"))
{
if (stack.empty())
System.out.println("1");
else
System.out.println("0");
}
else if (cmd.equals("pop"))
{
if (stack.empty())
System.out.println("-1");
else
System.out.println(stack.pop());
}
}
}
}
# Python
- List 이용
import sys
r = lambda: sys.stdin.readline().strip()
n = int(r())
stack = []
for k in range(n):
command = r()
if command[:4] == 'push':
num = int(command[4:])
stack.append(num)
elif command == 'top':
if len(stack) > 0:
print stack[-1]
else:
print -1
elif command == 'size':
print len(stack)
elif command == 'empty':
print '%d' % (len(stack) == 0)
elif command == 'pop':
if len(stack) > 0:
print stack.pop()
else:
print -1
반응형