#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