实验三 栈的实现及应用

先确定一个小目标:

建立一个数栈,数据类型为整型数据,分别用顺序栈和链栈完成以下功能:

1、编写取栈顶元素、入栈、出栈算法;

2、通过进制转化验证上述是三个算法(原数据,拟转化的进制从键盘输入,输出转化后的结果);


 

#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
typedef struct Stack
{
int data;
struct Stack * next;
}Stack;
Stack * InitStack()//初始化
{
Stack * p=(Stack*)malloc(sizeof(Stack));
if(p!=NULL)
{
p->data=0;
p->next=NULL;
}
return p;
}
Stack* push(Stack *head,int x)
{
Stack *p=(Stack *)malloc(sizeof(Stack));
if(p==NULL)
{
return NULL;
}
p->data=x;
p->next=head;
head=p;

return head;
}
Stack * pop(Stack *head)
{
if(head->next==NULL)
{
return NULL;
}
Stack *p;
p=head;
head=head->next;
free(p);
//printf("%d",head->data);
return head;
}
int top(Stack * head,int *l)
{
if(head->next==NULL)
return -1;
*l=head->data;
printf("%d",head->data);
return 0;
}
int visit(Stack * head)
{
Stack *p=head;
if(p->next==NULL)
{
printf("栈为空\n");
return -1;
}
while(p->next!=NULL)
{
printf("%d ",p->data);
p=p->next;
}
}
int StackEmpty(stack *head)//判断栈是否为空
{
if(head==NULL)
{
printf("栈为空");
}
else
return 1;

}
int main()
{
int a,b,x,l;
scanf("%d",&b);
Stack * s;
s=InitStack();
while(b!=0)
{
a=b%2;
b=b/2;
s=push(s,a);
}
visit(s);

}


 

转载于:https://www.cnblogs.com/accept/p/8175867.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值