LIFO(Last In First Out)이라는 개념을 가진 선형 자료구조

push(data) : 스택의 top에 데이터를 삽입pop : 스택의 top에 위치한 요소를 제거isEmpty : 스택이 비어있는지 확인isFull : 스택이 꽉 찼는지 확인peek or top: 스택의 top에 위치한 요소를 반환function sum(a, b) {
return a + b;
}
function print(value) {
console.log(value);
}
print(sum(5, 10));

지역변수, 변환 주소값, 매개변수가 저장되는 메모리 영역입니다.Stack을 Array로 표현할 수 있다.

Stack을 Linked List로 표현할 수 있다.

const stack = [];
// push
stack.push(1);
stack.push(2);
stack.push(3);
console.log(stack); // [ 1, 2, 3 ]
// pop
stack.pop();
console.log(stack); // [ 1, 2 ]
console.log(stack[stack.length - 1]); // 2
class Node {
// 생성자: new 키워드로 객체를 생성할때 호출되는 함수
constructor(value) {
this.value = value;
this.next = null;
}
}
class Stack {
// 생성자: new 키워드로 객체를 생성할때 호출되는 함수
constructor() {
this.top = null;
this.size = 0;
}
// 추가
push(value) {
const node = new Node(value); // 입력받은 값으로 새 노드 생성
node.next = this.top; // 새로 생성한 노드의 다음은 실행노드의 top을 가르킴
this.top = node; // 실행노드의 top은 노드를 가르킴
this.size += 1;
}
// 삭제
pop() {
const value = this.top.value; // 실행노드의 top의 value를 변수로
this.top = this.top.next; // 실행노드의 top의 next를 top으로
this.size -= 1;
return value;
}
size() {
return this.size;
}
}
const stack = new Stack();
stack.push(1);
stack.push(2);
stack.push(3);
console.log(stack.pop()); // 3
stack.push(4);
console.log(stack.pop()); // 4
console.log(stack.pop()); // 2
push '('와 pop ')'을 한 번씩 해서 빈 배열이 되어야 함(())()(()(function solution(s) {
const stack = [];
// for of : 배열 순회
for (const c of s) {
// 여는 괄호일 경우
if (c === '(') {
stack.push(c);
} else {
// 스택이 비어있는 경우
if (stack.length === 0) {
return false;
}
// 닫는 괄호일 경우
stack.pop();
}
}
// 빈 배열이라면 true, 아니라면 false
return stack.length === 0;
}
stack보다 메모리를 적게 사용 가능
function solution(s) {
let opened = 0;
for (const bracket of s) {
if (bracket === "(") opened += 1;
if (bracket === ")") opened -= 1;
if (opened < 0) return false;
}
return opened === 0;
}