C語言系列 : 堆疊Stack

複習以先進後出的堆疊(Stack)來處理資料。

完整程式碼:

// 使用stack 處理資料:新增,刪除,輸出

#include "pch.h"
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
void push_s(void);
void pop_s(void);
void list_s(void);
#define MAX 4
char item[MAX][20];
int point = -1;
int main()
{
	char chos;
	while (1) {
		printf("\n*****************************");
		printf("\n     <1> INSERT (push)");
		printf("\n     <2> DELETE (pop)");
		printf("\n     <3> LIST   (show)");
		printf("\n     <4> QUIT   ");
		printf("\n*****************************");
		printf("\nPlease enter yout choice...");
		chos = _getche();

		switch(chos) {
			case '1':
				push_s();
				break;
			case '2':
				pop_s();
				break;
			case '3':
				list_s();
				break;
			case '4':
				exit(0);
				break;
			default:
				printf("\n The input is error!!! \n");
		}

	}
}
void push_s() {
	//判斷是否可以push
	if (point > MAX - 1) {
		printf("\n\n Stack is full ! \n");
		//滿了
	}
	else {
		point++;
		printf("\n\n Please enter the an item <string> to insert: \n");
		scanf_s("%s",item[point]);
		//push
	}
}
void pop_s() {
	//判斷是否可以pop
	if (point == -1) {
		//空了
		printf("\n\n No item, the stack is empty! \n");
	}
	else {
		//可以delete
		printf("\n\n  Item %s is deleted! \n", item[point]);
		point--;
	}
	//pop
}
void list_s() {
	//顯示目前的stack
	printf("\n\n Item \n");
	printf("------------------------------\n");
	if (point > -1) {
		for (int i = 0; i <= point; i++) {
			printf("%s\n", item[point-i]);
		}
	}
	printf("------------------------------\n");
}

執行結果:

_______________________________________________

我們透過閱讀,拼湊出真實世界的面貌,
並在反覆的探索及思維中,打破由自我無知與偏見所建立的籓籬。