#include<stdio.h>
#include<stdlib.h>
//栈结点的定义
typedef struct stacknode
{
char data;
struct stacknode *next;
}stacknode;
//构造空栈
stacknode* creat_stack()
{
stacknode *top = NULL;
return top;
}
//入栈
stacknode* push(stacknode *top, char data) //在栈顶元素插入元素data
{
stacknode *p = (stacknode *)malloc(sizeof(stacknode)); //生成一个新节点
p->data = data;
p->next = top;
top = p;
return top;
}
//出栈
stacknode* pop(stacknode *top, char *t) //用t返回其值
{
stacknode *p = NULL;
if (top == NULL)
{
printf("栈为空,无法出栈!\n");
return NULL;
}
*t = top->data;
p = top;
top = top->next;
printf("元素%c已出栈\n", *t);
free(p);
return top;
}
//显示栈
void output(stacknode *top)
{
if (top == NULL)
printf("栈为空\n");
else
{
stacknode *p = (stacknode *)malloc(sizeof(stacknode));
p = top;
printf("栈遍历为:");
while(p != NULL)
{
printf("%c ", p->data);
p = p->next;
}
free(p);
printf("\n");
}
}
//求栈的结点个数
void Node_count(stacknode *top)
{
int count = 0;
stacknode *temp = top;
while(temp != NULL)
{
count++;
temp = temp->next;
}
printf("栈的结点个数为%d\n", count);
}
//销毁栈
stacknode* Destroy_stack(stacknode *top)
{
if(top == NULL)
printf("栈为空,无法销毁!\n");
else
{
stacknode *temp;
while(top != NULL)
{
temp = top->next;
free(top);
top = temp;
}
printf("栈已销毁!\n");
}
return NULL;
}
int main()
{
stacknode *top = creat_stack(); //建立一个空栈
printf(" 栈子系统\n");
printf("**************************************************\n");
printf("* 1-----入栈 *\n");
printf("* 2-----出栈 *\n");
printf("* 3-----显示栈 *\n");
printf("* 4-----求栈的结点个数 *\n");
printf("* 5-----销毁栈 *\n");
printf("* 0-----结束 *\n");
printf("**************************************************\n");
while (1)
{
int ch;
printf("\n***************************************************\n");
printf("请输入你要进行的操作对应的数字:");
scanf("%d",&ch);
getchar();
switch(ch)
{
case 1: //入栈
{
char data;
printf("请输入要入栈的元素:");
scanf("%c", &data);
getchar();
top = push(top, data);
printf("元素%c已入栈\n", data);
break;
}
case 2: //出栈
{
char t = 0; //*t用来接收出栈的值;
top = pop(top, &t);
break;
}
case 3: //显示栈
{
output(top);
break;
}
case 4: //求栈的结点个数
{
Node_count(top);
break;
}
case 5: //销毁栈
{
top = Destroy_stack(top);
break;
}
case 0:
{
printf("程序已结束!\n");
return 0;
}
default:
{
printf("输入的数值有误,请重新输入\n");
break;
}
}
}
return 0;
}
//
// _ooOoo_
// o8888888o
// 88" . "88
// (| ^_^ |)
// O\ = /O
// ____/`---'\____
// .' \\| |// `.
// / \\||| : |||// \
// / _||||| -:- |||||- \
// | | \\\ - /// | |
// | \_| ''\---/'' | |
// \ .-\__ `-` ___/-. /
// ___`. .' /--.--\ `. . ___
// ."" '< `.___\_<|>_/___.' >'"".
// | | : `- \`.;`\ _ /`;.`/ - ` : | |
// \ \ `-. \_ __\ /__ _/ .-` / /
// ========`-.____`-.___\_____/___.-`____.-'========
// `=---='
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// 佛祖保佑 永无BUG
//
栈的基本操作
最新推荐文章于 2022-12-20 20:39:00 发布