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();
}
}