μŠ€νƒ(Stack)

μŠ€νƒ(Stack)μ΄λž€?

Stack

  • μŠ€νƒ(Stack)은 μ˜μ–΄μ‚¬μ „μ—μ„œ (건초, λ°€μ§‘λ”°μœ„λ₯Ό μŒ“μ•„λ†“μ€) 더미λ₯Ό μ˜λ―Έν•œλ‹€κ³  ν•œλ‹€. μŠ€νƒμ˜ μ˜ˆλ‘œλŠ” 창고에 μŒ“μΈ λ°•μŠ€λ‚˜, 식당에 μŒ“μΈ μ ‘μ‹œ 더미등이 μžˆλ‹€.
  • λ°•μŠ€λ₯Ό μŒ“μ„λ•Œ μœ„μ—μ„œλΆ€ν„° ν•˜λ‚˜ν•˜λ‚˜ μŒ“λ“―μ΄, λ°˜λŒ€λ‘œ λ°•μŠ€λ₯Ό κΊΌλ‚Όλ•ŒλŠ” μœ„μ—μ„œλΆ€ν„° ν•˜λ‚˜ν•˜λ‚˜ κΊΌλ‚Έλ‹€. 이런 μž…μΆœλ ₯ ν˜•νƒœλ₯Ό LIFO(Last-In First-Out)이라고 ν•œλ‹€.

μŠ€νƒ μΆ”μƒμžλ£Œν˜•(Stack Abstract Data Type)

  • IsFull(): μŠ€νƒμ΄ λ‹€ μ°Όμ„λ•Œ, trueλ₯Ό λ°˜ν™˜ν•œλ‹€.
  • IsEmpty(): μŠ€νƒμ΄ λΉ„μ–΄μžˆμ„λ•Œ, trueλ₯Ό λ°˜ν™˜ν•œλ‹€.
  • push(): μŠ€νƒμ˜ 맨 μœ„μ— item을 μΆ”κ°€ν•œλ‹€.
  • pop(): μŠ€νƒμ˜ 맨 μœ„μ˜ μ›μ†Œλ₯Ό μ œκ±°ν•΄μ„œ λ°˜ν™˜ν•œλ‹€.
  • peek(): μŠ€νƒμ˜ 맨 μœ„μ˜ μ›μ†Œλ₯Ό μ œκ±°ν•˜μ§€ μ•Šκ³  λ°˜ν™˜ν•œλ‹€.

μŠ€νƒ(Stack)의 μ•Œκ³ λ¦¬μ¦˜

  • SP(Stack Pointer)의 μ΄ˆκΈ°κ°’μ— λ”°λΌμ„œ μ˜λ―Έκ°€ 쑰금 달라진닀.
    • If sp = 0
      push(item){
          if(Full) return; // Full >= N
          S[sp++] = item; // spλŠ” 넣을 자리λ₯Ό μ˜λ―Έν•œλ‹€.
      }
          
      pop(){
          if(Empty) return; // Empty: sp <= 0
          return S[--sp]
      }
      
    • If sp = -1
      push(item){
          if(Full) return; // Full >= N-1
          S[++sp] = item; // spλŠ” 넣은 자리λ₯Ό μ˜λ―Έν•œλ‹€.
      }
          
      pop(){
          if(Empty) return; // Empty: sp <= -1
          return S[sp--]
      }
      
  • μ—°κ²°λ¦¬μŠ€νŠΈλ₯Ό μ΄μš©ν•΄μ„œ μŠ€νƒμ„ κ΅¬ν˜„ν•˜λ©΄ λ°°μ—΄κ³ΌλŠ” 달리 크기의 μ œν•œμ΄ μ‚¬λΌμ§„λ‹€λŠ” μž₯점이 μžˆλ‹€. Linked List

    Node *S, *p;
    
    push(p){
      p -> Next = S;
      S -> p
    }
    
    Node* pop(){
      if(S == NULL) return NULL;
      p = S;
      S = S -> Next;
      return p;
    }
    

μŠ€νƒ(Stack) κ΅¬ν˜„

#include <stdio.h>
#define MAX_STACK_SIZE 100

typedef struct {
	int data[MAX_STACK_SIZE];
	int top;
} StackType;

void init_stack(StackType *s){
	s->top = -1;
}

int is_empty(StackType *s){
	return (s->top == - 1);
}

int is_full(StackType *s){
	return (s->top == (MAX_STACK_SIZE - 1));
}

void push(StackType *s, int item){
	if(is_full(s)) printf("Stack is FUll\n");
	else s->data[++(s->top)] = item;
}
int pop(StackType *s){
	if(is_empty(s)) printf("Stack is Empty\n");
	else return s->data[(s->top)--];
}
int peek(StackType *s){
	if(is_empty(s)) printf("Stack is Empty\n");
	else return s->data[s->top];
}
int main(void){	
	StackType s;
	
	init_stack(&s);
	push(&s, 1);
	push(&s, 2);
	push(&s, 3);
	printf("%d\n", pop(&s));
	printf("%d\n", pop(&s));
	printf("%d\n", pop(&s));
}

μŠ€νƒ(Stack)의 μ‚¬μš©μ‚¬λ‘€

  • ν•¨μˆ˜ 호좜
  • 미둜 μ°ΎκΈ°, κ·Έλž˜ν”„
  • 식(expression)의 처리(ν›„μœ„ ν‘œκΈ°λ²• 계산)
  • μ›Ή λΈŒλΌμš°μ € 방문기둝(λ’€λ‘œκ°€κΈ°)