源码:
//链栈
#include <iostream>
typedef int DataType;
//栈节点
typedef struct stacknode {
DataType data;
struct stacknode* next;
}StackNode;
//栈顶指针
typedef struct {
StackNode* top;
}LinkStack;
//--------------函数声明-----------------
int InitStack(LinkStack*); //初始化栈顶指针
int StackEmpty(LinkStack* S); //判栈空
void Menu(LinkStack* S); //用户菜单
int Push(LinkStack* S, DataType x); //进栈
int Pop(LinkStack* S, DataType* x); //出栈
int LengthStack(LinkStack* S); //栈的长度
int QingKongStack(LinkStack* S, DataType *data); //清空栈
void ShowData(StackNode* S); //读取栈内数据
//---------------------------------------
int main()
{
//栈顶指针
LinkStack* S = (LinkStack*)malloc(sizeof(LinkStack));
if(S == NULL){
printf("内存分配失败\n");
return 0;
}
InitStack(S);
Menu(S);
}
//初始化栈顶指针
int InitStack(LinkStack* S) {
S->top = NULL;
return 1;
}
//判栈空
int StackEmpty(LinkStack* S) {
return S->top == NULL; //如果为NULL返回1,说明栈空
}
//用户菜单
void Menu(LinkStack* S) {
DataType x,data;//data为出栈的数据,x为进栈的数据
int a;
while (1) {
printf("\n");
printf("1.进栈\t 2.出栈\t 3.长度\t 4.清空栈 5.按入栈顺序读数据\n");
printf("请输入选项:");
scanf_s("%d", &a);
switch (a) {
case 1:
printf("请输入插入数据:");
scanf_s("%d", &x);
if (Push(S, x)) {
printf("进栈成功\n");
printf("长度:%d\n", LengthStack(S));
}
else {
printf("进栈失败\n");
}
break;
case 2:
if (Pop(S, &data)) {
printf("删除成功\n");
printf("栈顶数据为:%d\n", data);
printf("长度:%d\n", LengthStack(S));
}
else {
printf("删除失败\n");
}
break;
case 3:
printf("长度:%d\n", LengthStack(S));
break;
case 4:
if (QingKongStack(S, &data)) {
printf("清空成功\n");
printf("长度:%d\n", LengthStack(S));
}
break;
case 5:
if (StackEmpty(S)) {
printf("栈空\n");
break;
}
StackNode * p = S->top; //指向栈顶指针
ShowData(p);
break;
}
}
}
//进栈
int Push(LinkStack* S, DataType x) {
StackNode* p = (StackNode*)malloc(sizeof(StackNode));
if (p == NULL) {
printf("内存分配失败\n");
return 0;
}
p->data = x;
p->next = S->top;
S->top = p;
return 1;
}
//出栈
int Pop(LinkStack* S, DataType *x) {
StackNode* p = S->top;
if (StackEmpty(S)) {
printf("栈空 ");
return 0;
}
*x = p->data;
S->top = p->next;
free(p);
return 1;
}
//栈的长度
int LengthStack(LinkStack* S) {
int j;
if (StackEmpty(S)) {
return j = 0;
}
StackNode* p = S->top;
j = 1;
while (p->next) {
j++;
p = p->next;
}
return j;
}
//清空栈
int QingKongStack(LinkStack* S,DataType *data) {
//如果不为空的情况下,进行出栈操作
while (!StackEmpty(S)) {
Pop(S, data);
}
return 1;
}
//读取栈内数据(按入栈顺序读取)
void ShowData(StackNode* p) {
if (p->next == NULL) {
printf("%d ", p->data);
}
else {
ShowData(p->next); //递归移动到栈底
printf("%d ", p->data);
}
}
|