본문 바로가기

[C언어]

[c언어] FILO(First in Last Out) Stack Linked List로 구현

#ifndef __LB_STACK_H__
#define __LB_STACK_H__

#define TRUE 1
#define FALSE 0

typedef int Data;

typedef struct _node {
	Data data;
	struct _node * next;

}Node;


typedef struct _listStack {
	Node * head;
}ListStack;

typedef ListStack Stack;

void StackInit(Stack * pstack);
int SIsEmpty(Stack * pstack);

void SPush(Stack* pstack, Data data);
Data SPop(Stack * pstack);
Data SPeek(Stack * pstack);


#endif // !__LB_STACK_H

먼저 헤더파일입니다.

 

Node에 보면 다음에 들어갈 next까지 들어가 있습니다.

 

#include<stdio.h>
#include<stdlib.h>
#include "ListBaseStack.h"

void StackInit(Stack * pstack) {
	pstack->head = NULL;
}


int SIsEmpty(Stack * pstack) {
	if (pstack->head == NULL)
		return TRUE;

	else
		return FALSE;

}



void SPush(Stack* pstack, Data data) {
	Node * newNode = (Node*)malloc(sizeof(Node));

	newNode->data = data;
	newNode->next = pstack->head;
	
	pstack->head = newNode;
}



Data SPop(Stack * pstack) {
	Data rdata;
	Node * rnode;

	if (SIsEmpty(pstack)) {
		printf("Stack Memeory error");
		exit(-1);
	}

	rdata = pstack->head->data;
	rnode = pstack->head;

	pstack->head = pstack->head->next;
	free(rnode);

	return rdata;

}


Data SPeek(Stack * pstack) {
	if (SIsEmpty(pstack)) {
		printf("Stack Memory ERROR");
		exit(-1);

	}

	else
		return pstack->head->data;
}


int main() {
	Stack stack;
	StackInit(&stack);


	for (int i = 1; i < 6; i++) {
		SPush(&stack,i);

	}

	while (!SIsEmpty(&stack))
		printf("%d", SPop(&stack));

	return 0;
}

메인소스코드입니다.

ps.

해당 컨텐츠는 컴공의 정석인 '열혈자료구조' 도서에서 발췌 및 구현하였습니다.