728x90
๋ฐ์ํ
1. ๋ฐฐ์ด STACK Code
#include <stdio.h>
#include <stdlib.h>
#define N 10
typedef int element; //๋์ค์ int๋ง char ๋ก ๋ฐ๊ฟ์ฃผ๋ฉด ๋จ
element stack[N];// ๋ฐฐ์ด์ ํฌ๊ธฐ๋ ๋์ค์ ๋ฐ๊ฟ ์๋ ์์ผ๋๊น
int top = -1;
// ๋
ธ๋ ์ฝ์
void push(int value){
if(top>=N -1){
printf("stack overflow");
exit(1);
}
top++;
stack[top] = value;
} //๊ฐ์ ์ฝ์
ํ๋ ํจ์
// ๋
ธ๋ ์ญ์
element pop(){
if (top<=-1){ //top = -1 : stack ๊ณต๋ฐฑ
printf("stack underflow");
exit(1);
}
element tmp;
tmp = stack[top];
top--;
return tmp;
}
int main(){
push(5); //stack: 5
push(3); //stack: 5 3
printf("%d\n", pop()); //stack: 5 , 3์ถ๋ ฅ
push(7); //stack: 5 7
printf("%d\n",pop()); //stack: 5, 7์ถ๋ ฅ
printf("%d\n",pop()); //stack: , 5์ถ๋ ฅ
}
2. linkedlist STACK Code
#include<stdio.h>
#include<stdlib.h>
typedef int element;
typedef struct stack_node* stack_pointer;
typedef struct stack_node{
element data;
stack_pointer link;
}snode;
//stack์ top ํ์ฌ ๋น์ด์์
stack_pointer top = NULL; //null: false ๊ฑฐ์ง
//์ฝ์
void push (element value){
stack_pointer news=(stack_pointer)malloc(sizeof(snode));
news->data = value;
news -> link = top;
top = news;
}
//0: ๊บผ์ง ๊ฑฐ์ง ์๋ฌด๊ฒ๋ ์์ NULL(0) = ๊บผ์ง, ๊ฑฐ์ง
//1: ์ผ์ง ์ฐธ ๋ฌด์ธ๊ฐ ์์
element pop(){
// stack =NULL
// top = NULL
// NULL == FALSE == 0
// !NULL == TRUE == 1
//if: ์ด ์กฐ๊ฑด์ด ์ฐธ์ด๋ผ๋ฉด ์์ ์๋ ์ฝ๋๋ฅผ ์คํํด์ค
//!๊ฑฐ์ง: ์ฐธ
if(!top){ //true์ผ๋
printf("์คํ์ ๊ฐ์ด ์์ต๋๋ค");
exit(1);
}//NULL์ผ๋ ๊ฑฐ์ง
// 0 NULL : false
// 1 ํน์ ๊ฐ์ด ์๋ ๊ฒฝ์ฐ if(2) : true
stack_pointer del = top;
element tmp = top->data ; //์ญ์ ํ ๋
ธ๋์ ๋ฐ์ดํฐ ๊ฐ
top = top->link;
free(del); //๋์ ํ ๋นํ ๋ฉ๋ชจ๋ฆฌ free
return tmp;
}
int main(void){
push(5); //stack: top -> 5
push(1); //stack: top -> 1 5
printf("%d\n", pop()); //stack: top -> 5, 1์ถ๋ ฅ
push(3); //stack: top -> 3 -> 5
printf("%d\n", pop()); //stack: top -> 5, 3 ์ถ๋ ฅ
printf("%d\n", pop()); //stack: top -> NULL, 5์ถ๋ ฅ
}
3. ์ฐ๊ฒฐ STACK - ์ฝ์
4. ์ฐ๊ฒฐ STACK - ์ญ์
728x90
๋ฐ์ํ