求:编写一个类,实现简单的栈操作(提示:用链表结构实现),按照先进后出的顺序。

 我来答
jegisk
2010-12-08 · TA获得超过819个赞
知道小有建树答主
回答量:632
采纳率:100%
帮助的人:460万
展开全部
程序1:顺序栈的实现和运算
#include<stdio.h>
#define MAXN 26
char stack[MAXN];
int top=0;

int push(char x)
{if (top >= MAXN)
return(1);
stack[top++]=x;
return(0);
}

int pop(char *p_y)
{if (top == 0)
return(1);
*p_y = stack[--top];
return(0);
}

void main()
{ int i;
char ch_x,ch_y;
printf("input the char you want to push\n");
scanf("%c",&ch_x);
while(ch_x!='0')
if (push(ch_x)==1) printf("failure!\n");
else
{printf("success!\n");
printf("input a char for ch_x to push\nch_x=");
getchar();
scanf("%c",&ch_x);}
i=0;
while(stack[i]!='\0')
{printf("%c ", stack[i]);
i++;}

if (pop(&ch_y)==1) printf("failure!\n");
else
{printf("success!\n");
printf("The pop char is %c\n",ch_y);}
for (i=top-1; i>=0; i--)
printf("%c ", stack[i]);
}
程序2:链栈的实现和运算
#include <stdio.h>
#include <malloc.h>
struct node{char data;
struct node *link;
};
typedef struct node NODE;
NODE * top = NULL;

void push_l(char x)
{NODE *p;
p = (NODE * )malloc(sizeof(NODE));
p->data = x;
p->link = top;
top = p;
}
int pop_l(char *p_y)
{NODE *p;
if (top == NULL)
return(1);
* p_y = top->data;
p = top;
top = top->link;
free(p);
return(0);
}

void main()
{ NODE *p;
char ch_x,ch_y;

printf("input the char you want to push\n");
scanf("%c",&ch_x);
while(ch_x!='0')
{push_l(ch_x);
getchar();
scanf("%c",&ch_x);}

p=(NODE*)malloc(sizeof(NODE));
p=top;
while(p!=NULL)
{printf("%c ",p->data);
p=p->link;}
printf("\n");

if (pop_l(&ch_y)==1) printf("failure!\n");
else
{printf("success!\n");
printf("The pop char is %c\n",ch_y);}

p=(NODE*)malloc(sizeof(NODE));
p=top;
while(p!=NULL)
{printf("%c ",p->data);
p=p->link;}
printf("\n");
}
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式