栈和队列的应用

1.读入一个有限大小的整数n,然后按输入次序的相反次序输出各元素的值。(用顺序栈实现)

2.利用栈完成数制转换。任意输入一个十进制数,将其转换成八进制数。(用顺序栈实现)

       

实验一:
#include “listack.cpp”
void read_write()
{
    stack S;
    int n,x;
    cout<<"请输入元素";
    cin>>n;
    init_stack(S);
    for(i=1;i<=n;i++)
    {
        cin>>x;
        push_stack(S,x);
    }
    while(stack_empty(S)!=TRUE)
    {
        stack_top(S,x);
        cout<<x;
        pop_stack(S);
    }
}
#include <stdio.h>
#include <malloc.h>
typedef char ElemType;
typedef struct linknode
{	
	ElemType data;				//数据域
	struct linknode *next;		//指针域
} LiStack;						//链栈类型定义
void InitStack(LiStack *&s)
{
	s=(LiStack *)malloc(sizeof(LiStack));
	s->next=NULL;
}
void DestroyQueue(LiStack *&s)
{
	LiStack *p=s->next;
	while (p!=NULL)
	{	
		free(s);
		s=p;
		p=p->next;
	}
	free(s);	//s指向尾结点,释放其空间
}
int StackLength(LiStack *s)
{
	int i=0;
	LiStack *p;
	p=s->next;
	while (p!=NULL)
	{	
		i++;
		p=p->next;
	}
	return(i);
}
bool StackEmpty(LiStack *s)
{
	return(s->next==NULL);
}
void Push(LiStack *&s,ElemType e)
{	LiStack *p;
	p=(LiStack *)malloc(sizeof(LiStack));
	p->data=e;				//新建元素e对应的节点*p
	p->next=s->next;		//插入*p节点作为开始节点
	s->next=p;
}
bool Pop(LiStack *&s,ElemType &e)
{	LiStack *p;
	if (s->next==NULL)		//栈空的情况
		return false;
	p=s->next;				//p指向开始节点
	e=p->data;
	s->next=p->next;		//删除*p节点
	free(p);				//释放*p节点
	return true;
}
bool GetTop(LiStack *s,ElemType &e)
{	if (s->next==NULL)		//栈空的情况
		return false;
	e=s->next->data;
	return true;
}
实验二:
//数组实现的栈
#include<iostream>
#define MaxSize 50
typedef int DataType;
using namespace std;
 
class stack
{
public:
    stack();
    bool isempty() const;
    bool isfull() const;
    void pop();
    void push(const DataType x);
    DataType get_top();
private:
    int count;
    DataType data[MaxSize];
};
 
stack::stack()
{
    count = 0;
}
 
bool stack::isempty() const
{
    if(0==count)
    return true;
    return false;
}
 
bool stack::isfull() const
{
    if(MaxSize==count)
    return true;
    return false;
}
 
void stack::pop()
{
    if(isempty())
    cout<<"underflow \n";
    count--;
}
 
void stack::push(const DataType x)
{
    if(isfull())
    cout<<"overflow \n";
    data[count]=x;
    count++;
}
 
DataType stack::get_top()
{
    if(isempty())
    cout<<"underflow \n";
    return data[count-1];
} 
 
//十进制转八进制
int main()
{
    cout<<"请输入一个十进制数:";
    int n;
    cin>>n;
    stack s;
    while(n!=0)
    {
        s.push(n%8);
        n=n/8;
    }
    cout<<"八进制数:"; 
    while(s.isempty()==false)
    {
        cout<<s.get_top();
        s.pop();
    }
} 

  • 9
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

简单编程王子

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值