작심 365
[c언어] linked list 로 stack 구현 본문
#include<stdio.h>
#include<stdlib.h>
typedef struct _stack { // stack 구조체 정의
struct _stack* next;
int data;
} stack;
stack* top; // 가장 마지막에 들어온 (가장 위에있는) 데이터를 가리키는 변수
void push(int item) { // 값 추가 함수
stack* tmp = (stack*)malloc(sizeof(stack));
if (tmp == NULL) { // 메모리가 full 일때
fprintf(stderr, "The memory is full\n");
exit(1);
}
tmp->next = top;
tmp->data = item;
top = tmp;
}
int pop() { // 값 삭제 함수
if (top == NULL) {
printf("The stack is empty\n");
exit(1);
}
int item;
stack* tmp = top;
item = tmp->data;
top = tmp->next;
free(tmp);
return item;
}
void printStack() { // stack 전체 출력 함수
stack* tmp = top;
while(tmp != NULL) {
printf("%d ", tmp->data);
tmp = tmp->next;
}
printf("\n");
}
int main(void) {
push(5);
push(4);
push(3);
push(2);
printStack();
pop();
printStack();
return 0;
}
결과

'자료구조' 카테고리의 다른 글
| [c언어] 인접행렬을 이용해서 그래프 구현 (0) | 2022.06.14 |
|---|
Comments