您的位置:首页 > 其它

关于栈和队列的三个题目

2017-06-08 17:37 267 查看
1. 用两个栈实现一个队列的功能(C++实现)

思路:

第一步,入队:用一个栈的push操作实现,将入队值压入一个栈中(栈一)

第二步,出队:在另一个栈中进行出栈操作(栈二):若栈二非空,直接从栈二中pop出即可

若栈二为空,则将栈一中的所有元素pop出来,一次push进栈二中,然后从栈二中pop出元素。

注:只有当stack2 为空时,才会从stack1中pop出元素push进stack2中。

C++代码如下:

#include <iostream>
#include <stack>

using namespace std;

template<class T>
struct MyQueue
{
void push(T &t)
{
s1.push(t);

}
T front()
{
if(s2.empty())
{
if(s1.size() == 0 ) throw;
while(!s1.empty())
{
s2.push(s1.top());
s1.pop();
}
}
return s2.top();
}
void pop()
{
if(s2.empty())
{
while(!s1.empty())
{
s2.push(s1.top());
s1.pop();
}
}
if(!s2.empty())
s2.pop();

}
stack<T> s1;
stack<T> s2;
};

int main()
{
MyQueue<int> mq;
int i;
for(i=0 ;i<10; ++i)
{
mq.push(i);
}
for(i=0; i<10; ++i)
{
cout<<mq.front()<<endl;
mq.pop();
}
return 0;
}


2. 编程实现栈的入栈和出栈操作

#include <iostream>
#include <stdio.h>
#include <string.h>
#include <conio.h>
using namespace std;

//定义一个栈
typedef struct student{
int data;
struct student *next;
}node;

typedef struct stackqueue{
node *zhandi,*top;
};

//定义入栈
queue *push(queue *HQ,int x){
node *s,*p;
s=(node*)malloc(sizeof(node));
s->data=x;
s->next=NULL;
//如果是空栈,则顶底都是s
if(HQ->zhandi==NULL){
HQ->zhandi=s;
HQ->top=s;
}else{
//不是空栈,先将栈顶的下一个指针指向s
//再将s定义为栈顶
HQ->top->next=s;
HQ->top=s;
}
return HQ;
}

//定义出栈:
queue *pop(queue *HQ){
node *p;int x;
if(HQ->zhandi==NULL){
cout<<"已经没有元素"<<endl;
}else{
x=HQ->zhandi->data;
p=HQ->zhandi;
if(HQ->zhandi==HQ->top){
HQ->zhandi=NULL;
HQ->top==NULL;
}else{
while(p->next!=HQ->top){
p=p->next;
}
HQ->top=p;
HQ->top->next=NULL;
}
return HQ;
}
}


3. 编程实现队列的入队和出队操作

#include <iostream>
#include <stdio.h>
#include <string.h>
#include <conio.h>

//首先定义队列
typedef struct student{
int data;
struct student *next;
}node;

typedef struct linkqueue{
node *first,*rear;
}queue;

//定义入队
queue *insert(queue *HQ,int x){
node *s;
s=(node *)malloc(sizeof(node));
s->data=x;
s->next=NULL;
if(HQ->rear==NULL){
//HQ没有队尾,则为空
//就让s成为他的队尾 和队头
HQ->first=s;
HQ->rear=s;
}else{
//先让队尾的下一个元素指向s
//将 s变为现在的队尾
HQ->rear->next=s;
HQ->rear=s;
}
return HQ;
}


//队列出队
queue *del (queue *HQ){
int x;
node *p;
if(HQ->first==NULL){
cout<<"队列为空,无元素移除"<<endl;
}
else{
x=HQ->first->data;
p=HQ->first;
//判断是否只有一个元素
if(HQ->first==HQ->rear){
HQ->first=NULL;
HQ->rear=NULL;
}else{
HQ->first=HQ->first->next;
free(p);
}
}
return HQ;
}


ok!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: