在這邊分享一下我實做堆疊的程式
程式的實做有分三種,最簡單的是直接使用陣列製作,另一種是使用鏈結串列
而我以下的程式是以實做出 Stack (透過 struct )的方法實做堆疊的操作,如下
#define MAX_STACK_SIZE 10
typedef struct {
int element[MAX_STACK_SIZE];
int top;
}Stack;
//宣告 : Stack s;
以下為程式實做部份:
#include <stdio.h>
#include <stdlib.h>
#define MAX_STACK_SIZE 10
typedef struct {
int element[MAX_STACK_SIZE];
int top;
}Stack;
Stack create(Stack); //initial the top for Stack
Stack push(Stack, int); //implements for push
Stack pop(Stack); //implements for pop
void showStack(Stack); //watch the stack now
bool isEmpty(Stack); //check is empty or not for stack
bool isFull(Stack); //check is full or not for stack
int main(void)
{
Stack s;
s = create(s);
printf("******************************************\n");
printf("****** input 1 means push ******\n");
printf("****** input 2 means pop ******\n");
printf("****** input 3 means show Stack ******\n");
printf("****** input other means exit ******\n");
printf("******************************************\n");
while(true)
{
int input = 0;
printf("--input[1 or 2 or other]-- : ");
scanf("%d", &input);
if(input == 1){ //push
int key;
printf("Plz input a number for push for Stack : ");
scanf("%d", &key);
s = push(s, key);
}else if(input == 2){ //pop
s = pop(s);
}else if(input == 3){
showStack(s); //view for stack
}else{
break;
}
}
showStack(s);
system("pause");
return 0;
}
Stack push(Stack s, int key)
{
if(isFull(s)){
printf("Stack is full !!\n");
}else{
s.top = s.top + 1;
s.element[s.top] = key;
printf("Success push %d in the Stack\n", key);
}
return s;
}
Stack pop(Stack s)
{
if(isEmpty(s)){
printf("Stack is empty !!\n");
return s;
}else{
int key = 0;
key = s.element[s.top];
s.top = s.top - 1;
printf("Success pop %d in the Stack\n", key);
return s;
}
}
bool isFull(Stack s)
{
return (s.top == MAX_STACK_SIZE-1);
}
bool isEmpty(Stack s)
{
return (s.top == -1);
}
Stack create(Stack s)
{
s.top = -1; //initial
return s;
}
void showStack(Stack s)
{
printf("now Stack is : ");
for(int i=0;i<=s.top;i++){
printf(" %d ", s.element[i]);
}printf("\n");
}
好厲害 這學期剛學到 資料結構好難..
回覆刪除我有一個疑問
if(input == 1){ //push
int key;
printf("Plz input a number for push for Stack : ");
scanf("%d", &key);
這部分
如果我想讓他可以輸入 字元 也可以輸入數字
該怎麼做
我很好奇 所以把
scanf("%d",&key);
改成
scanf("%s",&key);這樣竟然可以 但是我不知道為什麼