C/C++实现链栈代码
一、栈图
二、详细代码
#include <stdio.h>
#include <stdlib.h>
#include<iostream>
#include <malloc.h>
using namespace std;
#define STACKMAX 100
typedef struct stacknode
{
int data;
struct stacknode *next;
}Stacknode;
typedef struct
{
Stacknode *top;
}linkStack;
void Push(linkStack &s,int x)
{
Stacknode *p;
p =(Stacknode *)malloc(sizeof(Stacknode));
p->data = x;
p->next = s.top;
s.top = p;
}
void Pop(linkStack &s,int &x)
{
Stacknode * p;
if(s.top != NULL)
{
p = s.top;
x = p->data;
s.top = p->next;
free(p);
}
else
printf("\n\t\t栈为空!");
}
void show_stack(linkStack s)
{
Stacknode *p;
p = s.top;
if(p == NULL)
printf("\n\t\t栈为空!");
else
{
printf("\n\t\t栈元素为:");
while(p != NULL)
{
printf("%6d",p->data);
p = p->next;
}
printf("\n");
}
}
int main()
{
linkStack s;
int i = 1,j = 1,val,n;
char choice;
s.top = NULL;
while(1)
{
printf("\n");
printf("\n\t\t***************************************************");
printf("\n\t\t* 栈子系统 *");
printf("\n\t\t***************************************************");
printf("\n\t\t* 1------进 表 *");
printf("\n\t\t* 2------出 栈 *");
printf("\n\t\t* 3------显 示 *");
printf("\n\t\t* 0------退出程序 *");
printf("\n\t\t***************************************************");
printf("\n\t\t请选择菜单号:");
fflush(stdin);
choice = getchar();
switch(choice)
{
case '1':
while(1)
{
printf("\n\t\t键入一个整数并按回车:");
scanf("%d",&val);
if(val != 0)
Push(s,val);
else
break;
}
break;
case '2':
if(s.top != NULL)
{
Pop(s,val);
printf("\n\t\t出栈元素为:%6d\n",val);
}
else
printf("\n\t\t栈为空,无法出栈!");
break;
case '3':
show_stack(s);
break;
case 0:
exit(0);
default:
printf("\n\t\t输入错误!请重新输入!");
break;
}
}
return 0;
}