본문 바로가기

자료구조

스택이란

스택이란 ? 


삽입과 삭제로 이루어진 리스트. 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;
	}
}


'자료구조' 카테고리의 다른 글

그래프  (0) 2015.04.04
Heap/BST  (0) 2015.04.04
Binary tree(이진트리)  (0) 2015.04.04
트리  (0) 2015.04.04
  (0) 2015.04.04