链式栈的基本操作,如进栈,出栈,判栈空等

zhengyq21 2007-05-17 12:42:12
#include<iostream.h>
#include<malloc.h>
#define NULL 0
typedef struct snode{
int data;
struct snode *next;
}stack;
void push( struct snode *s,int x)
{struct snode *p;
p=( struct snode *)malloc(sizeof(snode));
cin>>x;
p->data=x;
p->next=s;
s=p;
}
void pop( struct snode *s )
{struct snode *p;
int e;
p=(struct snode *)malloc(sizeof(snode));
if(s->next==NULL) cout<<"error";
else
{p=s;
e=p->data;
s=p->next;
}
free(p);
cout<<e;
}
void print()
{struct snode *s;
if(s->next==NULL) cout<<"空栈 ";
else if(s->next!=NULL)
{cout<<s->data;
s=s->next;
}
}
void stackempty()
{struct snode *s;
if(s->next==NULL) cout<<"栈空";
else cout<<"栈非空";
}
void main()
{struct snode *s;
int f,x,e;
cin>>f;
while(1)
{
switch (f)
{case 'a':cin>>x;
push(s,x);
print();
stackempty();
break;
case 'b':pop(s);
print();
stackempty();
break;
}
}
}

有问题,帮我改一下吧.谢谢啦!



...全文
903 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
youfeng888 2010-10-27
  • 打赏
  • 举报
回复
xuke535010084 2010-10-27
  • 打赏
  • 举报
回复
mark ,jf
yuyunliuhen 2007-05-17
  • 打赏
  • 举报
回复
mark
winner8080 2007-05-17
  • 打赏
  • 举报
回复
差不多了,有不少错误
#include <iostream.h>
#include <malloc.h>
#define NULL 0
typedef struct snode
{
int data;
struct snode *next;
}stack;
//
void push( stack **s,int x)
{
stack *p;
p=( stack *)malloc(sizeof(snode));
//cin>>x;
p->data=x;
p->next=*s;
*s=p;
}
//
void pop( stack **s )
{
stack *p;
int e = 0 ;
p=(stack *)malloc(sizeof(snode));
if(NULL == (*s))
cout<<"空战";
else
{
p=*s;
e=p->data;
*s=p->next;
cout<<"出栈的数是:\t"<<e<<endl ;
}
free(p);
}
//
void print(stack **s)
{
//stack *s;
if( *s == NULL)
cout<<"空栈 ";
else if((*s)!=NULL)
{
cout<<"出栈的数是:\t"<<(*s)->data<<endl ;
*s = (*s)->next;
}
}
//
void stackempty(stack **s)
{
//stack *s;
if(*s == NULL)
cout<<"栈空"<<endl ;
else
cout<<"栈非空"<<endl ;
}
//
void main()
{
stack *s= NULL ;// = new stack();
int f,x,e;
puts("输入1(入栈)或2(出栈)\n") ;
cin>>f;
while(1)
{
switch (f)
{
case 1:
puts("输入入栈的数:\t") ;
cin>>x;
push(&s,x);
print(&s);
stackempty(&s);
break;
case 2:
pop(&s);
print(&s);
stackempty(&s);
break;
default:
break ;
}
break ;
}
system("pause") ;
}
winner8080 2007-05-17
  • 打赏
  • 举报
回复
既然你typedef struct snode{...

下面就直接用stack,而不用struct snode,当然要用也可以
winner8080 2007-05-17
  • 打赏
  • 举报
回复
先说楼主的代码风格不怎么样
然后再看看代码

64,654

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧