스택이란 ?
삽입과 삭제로 이루어진 리스트. Last In, First out.
응용 : 수식계산(컴퓨터는 수식의 우선순위를 모르니까), 프로그램 순서.
어레이로 구현
public class ArrayStack { int[] stack; int top; public ArrayStack() { super(); stack = new int[100]; top = -1; } void push(int num) { top++; stack[top] = num; System.out.println(num+" is pushed"); } int pop() { int num = stack[top]; top--; return num; } }
리스트로 구현
public class ListStack { LinkedList top; void push(int num) { LinkedList newOne = new LinkedList(num); System.out.println(num+" is pushed"); newOne.link = top; //서로 연결 시켜주기 위해서 //newOne과 이전의 top을 연결 시켜준다. top = newOne; //새로 들어온 것이 top이 된다. } int pop() { int num = top.data; //top의 데이타를 우선 메모리에 저장시켜두고 top = top.link; //top의 link랑 연결되어 있는 (그 밑의 객체)로 top을 옮겨줌. return num; } }