黑马程序员技术交流社区
标题:
栈和队列实验!
[打印本页]
作者:
漩涡java
时间:
2014-2-20 16:22
标题:
栈和队列实验!
#include<iostream>
using namespace std;
typedef int Elemtype;
typedef struct snode{
Elemtype data;
struct snode *next;
}Linkstack;
void Initstack(Linkstack **top)
{*top=(Linkstack *)malloc(sizeof(Linkstack));
(*top)->next=NULL;
cout<<"栈初始化成功!\n";
}
int push(Linkstack **top,Elemtype x)
{
Linkstack *s;
s=(Linkstack*)malloc(sizeof(Linkstack));
s->data=x;
s->next=(*top)->next;
(*top)->next=s;
return 1;
}
int Empty(Linkstack **top)
{return ((*top)->next==NULL?1:0);}
int pop(Linkstack **top,Elemtype *x)
{
Linkstack *s;
if(Empty(top))
{
cout<<"\n 栈为空!";
return 0;
}
s=(*top)->next;
*x=s->data;
(*top)->next=s->next;
free(s);
return 1;
}
//队列功能的实现
typedef struct qnode{
Elemtype data;
struct qnode *next;
}qtype;
typedef struct sqtr{
qtype *front,*rear;
}squeue;
void Initqueue(squeue *LQ)
{
qtype *p;
p=(qtype *)malloc(sizeof(qtype));
p->next=NULL;
LQ->front=LQ->rear=p;
cout<<"队列初始化成功!\n";
}
int Enqueue(squeue *LQ,Elemtype x)
{
qtype *s;
s=(qtype *)malloc(sizeof(qtype));
s->data=x;
s->next=LQ->rear->next;
LQ->rear->next=s;
LQ->rear=s;
return 1;
}
int Empty(squeue *LQ)
{return(LQ->front==LQ->rear?1:0);}
int Outqueue(squeue *LQ,Elemtype *x)
{
qtype *p;
if(Empty(LQ))
{
cout<<"队列为空!";
return 0;
}
p=LQ->front->next;
*x=p->data;
LQ->front->next=p->next;
if(LQ->front->next==NULL)
LQ->rear=LQ->front;
free(p);
return 1;
}
void Dectoothers(int n,int b)
{
char B[]="0123456789ABCDEF";
Elemtype a,c;
Linkstack *top;
squeue LQ;
Initstack (&top);
Initqueue(&LQ);
cout<<n<<"转化为"<<b<<"进制数为:";
while(n)
{
push(&top,n%b);
n=n/b;
}
while(!Empty(&top))
{
pop(&top,&a);
Enqueue(&LQ,a);
Outqueue(&LQ,&c);
cout<<B[c]<<' ';
}
cout<<endl;
}
int main()
{
char s;
int n,b;
do
{
cout<<"请输入要转化成其他进制数的非负数:";
cin>>n;
cout<<"请输入需要转化成的进制:";
cin>>b;
Dectoothers(n,b);
cout<<"需要结束请输入N/n,继续输入Y/y:";
cin>>s;
}while((s!='n') && (s!='N'));
return 0;
}
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2