题解 | 栈1
调用函数对栈进行初始化,需传递二级指针;
当然,如果在main函数中对其进行初始化,直接初始化即可。
- 本篇采用c语言编写,调用函数初始化栈,该栈为链栈,带头结点。
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define LEN sizeof(StackNode)//方便malloc函数书写
typedef struct StackNode {//栈的结点结构体
int data;
struct StackNode* next;
} StackNode, *LinkStack;
void initStack(LinkStack* h);//初始化栈
void push(LinkStack h);//入栈
void pop(LinkStack h);//出栈
void top(LinkStack h);//获取栈顶元素
int count = 0;//栈的结点个数(不包括头结点)
int main() {
int n;//操作次数
LinkStack h;//指向头结点
initStack(&h);//初始化栈
//printf("\n请输入操作次数:\t");
scanf("%d", &n);
if (n >= 1 && n <= 100000) {
while (n--) {
int flag = 0;//判断是否输入错误
char a[10];
//printf("\n请输入操作函数:\t");
scanf("%s", a);
if (strncmp(a, "push", 4) == 0) {
push(h);
flag = 1;
}
if (strncmp(a, "pop", 3) == 0) {
pop(h);
flag = 1;
}
if (strncmp(a, "top", 3) == 0) {
top(h);
flag = 1;
}
if (flag == 0) {
printf("输入错误。\n");
}
}
} else {//n输入错误
printf("error\n");
}
return 0;
}
void initStack(LinkStack* h) {//初始化栈
(*h) = (LinkStack)malloc(LEN);
(*h)->next = NULL;
}
void push(LinkStack h) {//入栈
StackNode* p;
int x;
//printf("\n请输入入栈x的值:\t");
scanf("%d", &x);
p = (StackNode*)malloc(LEN);
p->data = x;
p->next = h->next;
h->next = p;
count++;
}
void pop(LinkStack h) {//出栈
if (count == 0) {
printf("error\n");
return ;
}
StackNode* p;
p = h->next;
printf("%d\n", p->data);
h->next = h->next->next;
free(p);
count--;
}
void top(LinkStack h) {//获取栈顶元素
if (count == 0) {
printf("error\n");
return ;
}
printf("%d\n", h->next->data);
}