JavaScrpt/자료구조

JavaScript Stack - 스택 만들기, Data Structures

carrotweb 2022. 4. 17. 19:01
728x90
반응형

이전 원형 큐(Circular Queue - 또는 환상 큐)처럼 JavaScript의 Array 객체의 메서드를 사용하지 않고 스택(Stack)을 만들어 보겠습니다.

스택(Stack)은 한쪽으로 데이터를 쌓아 올리는 구조입니다.

프로그램에서 데이터의 위치를 top이라고 합니다.

​[파란색 화살이 top]

스택에 데이터를 추가하기 위해서 top의 위치에 1을 더한 후 데이터를 추가합니다. 그리고 스택에서 데이터를 가져오기 위해서는 top의 위치에 데이터를 가져오고 top에서 1을 뺍니다. top이 -1이면 스택에 데이터가 없는 상태이고 top의 위치가 스택의 마지막 위치와 같으면 더 이상 스택에 데이터를 넣을 수 없는 포화 상태입니다.

반응형

 

 

스택(Stack) 객체 생성하기

JavaScript에서 객체 생성하는 방법은 "JavaScript Object - 객체 생성"(https://carrotweb.tistory.com/184)를 참고하시기 바랍니다.

function()으로 stack 객체를 선언하겠습니다.

객체 생성할 때 스택의 크기를 받아서 스택을 초기화합니다.

var Stack = function(stackSize) {
	// Array 객체 생성
	this.stack = [];
	// 데이터 위치
	this.top = -1;
	// 스택의 크기
	this.stackSize = stackSize;
	// 스택 초기화
	for (var index = 0; index < stackSize; index++) {
		this.stack.push(null);
	}
	// 스택에 데이터 넣기 함수
	this.push = function(data) {
		var result = true;
		if (this.isFull()) {
			console.log("Stack Full");
			result = false;
		} else {
			this.top++;
			this.stack[this.top] = data;
		}
		return result;
	}
	// 스택에서 데이터 가져오기 함수
	this.pop = function() {
		var result = null;
		if (this.isEmpty()) {
			console.log("Stack Empty");
		} else {
			result = this.stack[this.top];
			this.stack[this.top] = null;
			this.top--;
		}
		return result;
	}
	// 스택에 데이터가 공백 상태인지 확인하는 함수
	this.isEmpty = function() {
		return (this.top == -1);
	}
	// 스택에 데이터가 포화 상태인지 확인하는 함수
	this.isFull = function() {
		return (this.top == this.stackSize - 1);
	}
	// 스택 정보 출력 함수
	this.consoleLog = function() {
		console.log(this.stack);
		console.log("top: " + this.top);
	}
}

스택의 데이터와 top의 위치를 알기 위해서 console로 출력하는 consoleLog 함수를 만들었습니다.

 

function()으로 선언된 스택(Stack)을 생성(new) 하겠습니다.

var stack = new Stack(3);

console.log(stack);
--> CircularQueue {stack: Array(3), top: -1, stackSize: 0, push: ƒ, pop: ƒ, isEmpty: ƒ, isFull: ƒ, consoleLog: ƒ}
console.log(typeof stack);
--> object
console.log(stack instanceof Object);
--> true
console.log(stack instanceof Stack);
--> true
stack.consoleLog();
--> (3) [null, null, null]
--> top: -1

 

생성된 스택(Stack)에 데이터를 넣고 가져오겠습니다.

// 데이터 넣기
stack.push("Data 1");
stack.consoleLog();
--> (3) ['Data 1', null, null]
--> top: 0

// 데이터 넣기
stack.push("Data 2");
stack.consoleLog();
--> (3) ['Data 1', 'Data 2', null]
--> top: 1

// 데이터 가져오기
var popData = stack.pop();
console.log(popData);
--> Data 2
stack.consoleLog();
--> (3) ['Data 1', null, null]
--> top: 0

push() 함수의 리턴 값이 false 이면 스택에 데이터를 더 이상 추가할 수 없는 포화 상태이고 pop() 함수의 리턴 값이 null이면 스택에 데이터가 없는 상태입니다.

728x90
반응형