코딩 이야기

[C언어] 스택 삽입(push), 삭제(pop),체크(peek) 구현

고주망고 2021. 11. 1. 16:31

안녕하세요 이번 포스팅에서는 스택을 구현 해보겠습니다

스택은 삽입, 삭제, 체크가 매우 쉬워서 중요한 자료구조라고 할수 있습니다.

 

실행 예시


#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);
}