关于栈和队列的三个题目
2017-06-08 17:37
267 查看
1. 用两个栈实现一个队列的功能(C++实现)
思路:
第一步,入队:用一个栈的push操作实现,将入队值压入一个栈中(栈一)
第二步,出队:在另一个栈中进行出栈操作(栈二):若栈二非空,直接从栈二中pop出即可
若栈二为空,则将栈一中的所有元素pop出来,一次push进栈二中,然后从栈二中pop出元素。
注:只有当stack2 为空时,才会从stack1中pop出元素push进stack2中。
C++代码如下:
2. 编程实现栈的入栈和出栈操作
3. 编程实现队列的入队和出队操作
ok!
思路:
第一步,入队:用一个栈的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!
相关文章推荐
- 关于C++队列操作(并附上一道Boring题目)
- 暑期个人赛--第八场--B(关于手写队列的启示+题目有坑)
- 关于栈和队列的题目总结
- 关于缓冲区/池设计中的三个队列
- 关于linux内核中等待队列的问题!
- 在北京软通动力面试的时候难倒我的三个题目
- 关于ASP.NET AJAX的三个视频
- 关于一个CCIE考试题目的研究(重分发)
- 关于网络安全方面的岗位面试题目
- 三个关于计算机科学的最大真理(zt)
- 2道关于 SQLServer 数据库方面的题目:
- 关于毕业设计题目的一些思考
- 关于CURSOR_SHARING三个取值的区别
- 几道不错的关于AI编程的题目
- ==关于三个作者==
- 关于数据库设计的三个范式
- 百度一道关于算法的面试题目
- 关于用优先级队列和树解决中缀表达式计算的一点比较
- 题目:一数列有如下特点,第1,2,3三个数为1,1,1。从第四个数开始,该数是前面三个数之和。
- 关于执行队列和工作管理器