안녕하세요 이번 포스팅에서는 스택을 구현 해보겠습니다
스택은 삽입, 삭제, 체크가 매우 쉬워서 중요한 자료구조라고 할수 있습니다.
#define _CRT_NO_SECURE_WARNINGS_
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef int element;
typedef struct stackNode {
element data;
struct stackNode* link;
}stackNode;
stackNode* top;
int isEmpty() {
if (top == NULL) {
return 1;
}
else {
return 0;
}
}
void push(element item) {
stackNode* newNode;
newNode = (stackNode*)malloc(sizeof(stackNode));
newNode->data = item;
newNode->link = top;
top = newNode;
}
element pop() {
stackNode* temp;
temp = top->data;
top = top->link;
return temp;
}
element peek() {
stackNode* temp;
temp = top;
return temp->data;
}
void printStack() {
stackNode* temp;
temp = top;
printf(" Stack = ( ");
if (temp == NULL) {
printf("값이 없습니다 )\n");
}
else {
while (temp != NULL){
printf("%2d", temp->data);
temp = temp->link;
}
printf(" -> NULL )\n");
}
}
void main() {
element item;
top = NULL;
printf("연결 자료구조를 이용한 스택 연산\n");
printStack();
push(1); printf("\npush(1) 실행결과:");
printStack();
push(2); printf("\npush(2) 실행결과:");
printStack();
push(3); printf("\npush(3) 실행결과:");
printStack();
item = peek(); printf("\npeek 실행:");
printStack();
printf("peek: %d \n", item);
item = pop(); printf("\npop 1회 실행:");
printStack();
printf("pop 1회: %d \n", item);
item = pop(); printf("\npop 2회 실행:");
printStack();
printf("pop 2회: %d \n", item);
item = pop(); printf("\npop 3회 실행:");
printStack();
printf("pop 3회: %d \n", item);
}
'코딩 이야기' 카테고리의 다른 글
[C언어] 연결리스트를 이용하여 큐 구현하기 (0) | 2021.11.04 |
---|---|
[C언어] 스택(stack)을 이용하여 수식의 괄호 쌍 검사 (0) | 2021.11.02 |
[C언어] 이중 연결 리스트를 이용한 노드 삽입, 삭제 연산 구현 (0) | 2021.11.01 |
[C언어] 원형 연결 리스트 노드 삽입 탐색 삭제를 구현해보자 (0) | 2021.10.30 |
[C언어] 단순 연결 리스트에서 노드 삭제, 탐색 함수 구현 (0) | 2021.10.20 |