#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>#define MAXSIZE 100//链栈结点结构
typedef struct LinkStack {int val;struct LinkStack* next;
}LinkStack;//打印所有栈中元素
void Print(LinkStack* s) {while (s) {printf("%d\t", s->val);s = s->next;}printf("\n");
}//入栈
void Push(LinkStack** s, int v) {LinkStack* tmp = (LinkStack*)malloc(sizeof(LinkStack));tmp->val = v;tmp->next = *s;*s = tmp;
}//出栈
bool Pop(LinkStack** s, int* popVal) {if (*s == NULL)return false;*popVal = (*s)->val;LinkStack* tmp = *s;*s = (*s)->next;free(tmp);return true;
}//取栈顶元素
bool getTop(LinkStack* s, int* v) {if (s == NULL)return false;*v = s->val;return true;
}//判断栈是否为空
bool isEmpty(LinkStack* s) {if (s == NULL)return true;else return false;
}int main() {//初始化一个空栈LinkStack* s = (LinkStack*)malloc(sizeof(LinkStack));s = NULL;//判断栈是否为空if (isEmpty(s))printf("s is empty.\n");else printf("s is not empty.\n");//入栈Push(&s, 1);//打印所有栈中元素Print(s);//入栈Push(&s, 2);//打印所有栈中元素Print(s);//出栈int popVal = 0;Pop(&s, &popVal);//打印所有栈中元素Print(s);//打印出栈元素printf("%d\n", popVal);//取栈顶元素int topVal = 0;getTop(s, &topVal);//打印栈顶元素printf("%d\n", topVal);//打印所有栈中元素Print(s);return 0;
}
输出:
s is empty.
1
2 1
1
2
1
1