Skip to content

Instantly share code, notes, and snippets.

@dalcon10028
Last active June 3, 2020 07:57
Show Gist options
  • Save dalcon10028/51310d6bef6ce17c36308c7022b48284 to your computer and use it in GitHub Desktop.
Save dalcon10028/51310d6bef6ce17c36308c7022b48284 to your computer and use it in GitHub Desktop.
연결리스트를 이용한 스택
#include <stdio.h>
#include <stdlib.h>
struct _node {
char data;
struct _node *link;
};
typedef struct _node node;
/* 스택 포인터의 초기화 */
node *top = NULL;
int menu();
void view_stack(), push_menu(), pop_menu();
void topexam_menu(), isempty_menu();
void push(char obj);
char pop();
int isempty();
void main() {
int choice;
do {
choice = menu();
switch(choice) { // 선택한 메뉴를 치환
case 1: push_menu();
break;
case 2: pop_menu();
break;
case 3: topexam_menu();
break;
case 4: isempty_menu();
break;
}
}while(choice!=5);
}
/* 사용자가 메뉴를 선택하여 선택한 번호를 반환 */
int menu() {
int i;
printf("Basic Stack Program 1.0\n");
printf("1. push\n");
printf("2. pop\n");
printf("3. topexam\n");
printf("4. isempty\n");
printf("5. quit\n");
do{
printf("Choose your selection: ");
scanf("%d", &i);
}while(i<1 || i>5);
return i;
}
/* 전체 스택 보기 */
void view_stack() {
node *temp;
// top노드가 null을 가르키면 빈 스택
if(top==NULL) return;
// 제일 위 노드(top)부터 아래로 데이터를 확인합니다.
temp = top;
while(temp->link!=NULL){
printf("%c | ", temp->data);
temp = temp->link;
}
/* 마지막 노드 출력 */
printf("%c |\n", temp->data);
}
/* 스택에 객체를 삽입하는 메뉴 */
void push_menu(void) {
char obj;
printf("Insert New Object : ");
getchar();
scanf("%c", &obj);
push(obj);
/* push 연산 성공하면 전체 스택 보기 */
view_stack();
}
void push(char obj) {
node *current;
/* 새로 주소를 받아 노드를 생성합니다. */
/* top(맨 위)의 위치를 새로 생성한 노드로 지정합니다 */
current = (node *) malloc(sizeof(node));
current->data = obj;
current->link = top;
top = current;
}
void pop_menu() {
// pop 할 내용이 있으면 pop하고 스택 전체를 보여줍니다.
char obj;
if(obj=pop()) view_stack();
}
char pop(){
char ch;
node *temp;
// 비어있으면 0반환
if(isempty()) return 0;
// top 다음 노드(top 밑에 있는 노드)로 연결하고 메모리를 풀어줍니다.
ch = top->data;
temp = top;
top = top->link;
free(temp);
// 제거되는 노드 데이터 반환
return ch;
}
int isempty(){
// top이 null이면 빈스택
if(top==NULL) {
printf("Stack is empty!!\n");
return 1;
}else return 0;
}
void isempty_menu(){
if(!isempty()) printf("Stack is not empty\n");
}
void topexam_menu() {
if(!isempty()) printf("Top data : %c\n", top->data);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment