【面试题007】栈和队列
用两个栈来模拟一个队列。
在出队之前,一个辅助栈如果为空的话需要把第一个栈中的所有元素弹出压入这个栈中,栈顶的那个元素就是要出队的元素;
如果辅助栈不为空的话,栈顶元素就是要出队的元素;
TwoStack.cpp:
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
#include <iostream>
#include <cstdio> #include "Queue.h" using namespace std; void Test(char actual, char expected) { if(actual == expected) printf("Test passed. "); else printf("Test failed. "); } int main() { CQueue<char> queue; queue.appendTail('a'); queue.appendTail('b'); queue.appendTail('c'); char head = queue.deleteHead(); Test(head, 'a'); head = queue.deleteHead(); Test(head, 'b'); queue.appendTail('d'); head = queue.deleteHead(); Test(head, 'c'); queue.appendTail('e'); head = queue.deleteHead(); Test(head, 'd'); head = queue.deleteHead(); Test(head, 'e'); return 0; } |
测试结果:
Test passed.
Test passed. Test passed.
Test passed.
Test passed.
Queue.h:
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 |
#ifndef _QUEUE_H_
#define _QUEUE_H_ #include <stack> #include <exception> using namespace std; template <typename T> class CQueue { public: CQueue(void); ~CQueue(void); // 在队列末尾添加一个结点 void appendTail(const T &node); // 删除队列的头结点 T deleteHead(); private: stack<T> stack1; stack<T> stack2; }; template <typename T> CQueue<T>::CQueue(void) { } template <typename T> CQueue<T>::~CQueue(void) { } template<typename T> void CQueue<T> ::appendTail(const T &element) { stack1.push(element); } template<typename T> T CQueue<T>::deleteHead() { if(stack2.size() <= 0) { while(stack1.size() > 0) { T &data = stack1.top(); stack1.pop(); stack2.push(data); } } if(stack2.size() == 0) throw new exception(); T head = stack2.top(); stack2.pop(); return head; } #endif /*_QUEUE_H_*/ |
Queue.cpp:
1
2 |
#include "Queue.h"
#include <queue> |
Makefile:
1
2 3 4 5 6 7 8 9 10 11 12 |
.PHONY:clean
CPP=g++ CFLAGS=-Wall -g BIN=test OBJS=TwoStack.o Queue.o LIBS= $(BIN):$(OBJS) $(CPP) $(CFLAGS) $^ -o $@ $(LIBS) %.o:%.cpp $(CPP) $(CFLAGS) -c $< -o $@ clean: rm -f *.o $(BIN) |