C언어 스택
스택 많이 사용되는 자료구조입니다. Fist in Last out의 구조로 되어 있습니다.
예를들어 1,2,4,5,6의 순서로 스택에 저장되어 있으면 출력은 6,5,4,2,1의 순서입니다.
보통 데이터를 넣는 것은 Push
데이터를 빼는 것은 Pop이라고 합니다. input, output으로 해도 됩니다.
중요한건 어떻게 저장되어 있냐는 거니까요
스택에 Push 할때는 2,3,1,7의 순서로 저장되고 Pop일 때는 7,1,3,2의 순서입니다.
이를 리스트로 나타내면 다음과 같은 과정입니다.
리스트 스택 삽입과정(Push)
#include <stdio.h> #include <stdlib.h> #define INF 99999999 typedef struct { int data; struct Node* next; } Node; typedef struct { Node* top; } Stack; void push(Stack* stack, int data) { Node* node = (Node*)malloc(sizeof(Node)); node->data = data; node->next = stack->top; stack->top = node; } void pop(Stack* stack) { if (stack->top == NULL) { printf("UnderFlow.\n"); return -INF; } Node* node = stack->top; int data = node->data; stack->top = node->next; free(node); return data; } void show(Stack* stack) { Node* cur = stack->top; while (cur != NULL) { printf("%d\n", cur->data); cur = cur->next; } }
댓글
댓글 쓰기