基本栈和队列 及后续面试题
来源:互联网 发布:游戏美化软件 编辑:程序博客网 时间:2024/06/06 03:15
基本栈和队列
栈Stack-------后进先出
#pragma once#include<cassert>#include<iostream>using namespace std;template<class T>class Stack{public:Stack():_a(NULL), _size(0), _capacity(0){}~Stack(){if (_a){delete[] _a;_size = _capacity=0;}}void Push(const T& x){CheckCapacity();_a[_size++] = x;}void Pop(){assert(_size > 0);_size--;}T& Top(){assert(_size > 0);return _a[_size - 1];} void CheckCapacity(){if (_size >= _capacity){_capacity = (_capacity == 0) ? 3 : _capacity * 2;T* tmp = new T[_capacity];for (size_t i = 0; i < _size; i++){tmp[i] = _a[i];}delete[]_a;_a = tmp;}}bool Empty(){return _size == 0;}size_t Size(){return _size;}protected:T* _a;size_t _size;size_t _capacity;};
队列Queue----------先进先出
#pragma once#include<cassert>#include<iostream>using namespace std;template<class T>struct QueueNode{T _data;QueueNode<T>* _next;QueueNode(const T& x):_data(x), _next(NULL){}};template<class T>class Queue{typedef QueueNode<T> Node;public:Queue():_head(NULL),_tail(NULL){}~Queue(){if (_head){delete[] _head;}_head = NULL;}void Push(const T& x){if (_tail == NULL){_head = _tail = new Node(x);}else{_tail->_next = new Node(x);_tail = _tail->_next;}}void Pop(){if (_head){ Node* cur = _head ->_next ; delete _head; _head = cur;}}T& Front(){assert(_head);return _head->_data;}size_t Size(){size_t count = 0;Node* cur = _head;while (cur){++count;cur = cur->_next;}return count;}bool Empty(){return _head == NULL;}protected:Node* _head;Node* _tail;};
#include"Queue.h"#include"Stack.h"#include<windows.h>void TestStack(){Stack<int> s1;Stack<int> s2;s1.Push(1);s1.Push(2);s1.Push(3);s1.Push(4);while (!s1.Empty()){cout << s1.Top() << " ";s2.Push(s1.Top());s1.Pop();}cout << endl;while (!s2.Empty()){cout << s2.Top() << " ";s2.Pop();}}void TestQueue(){Queue<int> q1;q1.Push(1);q1.Push(2);q1.Push(3);q1.Push(4);while (q1.Size() > 0){cout << q1.Front() << " ";q1.Pop();}}int main(){//TestStack();TestQueue();system("pause");return 0;}
面试题,静候更新.....阅读全文
0 0
- 基本栈和队列 及后续面试题
- 栈和队列面试题
- 栈和队列面试题
- 栈和队列面试题
- 【面试题】栈和队列的面试题
- 栈和队列面试题总结
- 【面试题七】栈和队列
- 栈和队列面试题(一)
- 栈和队列面试题(二)
- 栈和队列面试题(三)
- 栈和队列面试题(四)
- 栈和队列常见面试题
- 栈和队列 相关 面试题
- 栈和队列相关面试题2
- 队列和栈的面试题
- 栈和队列的常见面试题
- /*****/栈和队列常见面试题
- 队列和栈相关面试题总结
- 【51nod】1009 数字1的数量
- leetcode.array--35. Search Insert Position
- (完)learn python第四章:异常处理机制和文件(第一节:异常处理机制)
- python网络数据学习范例-正则表达式+lambda函数
- PHP多维数组去重
- 基本栈和队列 及后续面试题
- NAS存储
- C++Primer Plus(第六版) 第十六章 第八题
- mock测试
- Spring注解@Component、@Repository、@Service、@Controller区别
- <序列DP>O(nlogn)的最长上升子序列
- 整体二分小结
- bfs学习之寻找二叉树每层最大值
- detect获取到手机型号