棧的定義
棧是一種只能在一端進行插入或刪除操作的線性表。
表中允許進行插入、刪除操作的一端稱爲棧頂。棧頂的當前位置是動態的,由棧頂指針來指示。表的另一端稱爲棧底。當棧中沒有數據元素時,稱爲空棧。棧的插入操作通常稱爲進棧或入棧,棧的刪除操作通常稱爲退棧或出棧。
棧的特殊性在於限定插入和刪除數據元素的操作只能在線性表的一端進行,所以棧的特點是後進先出(Last In First Out),棧簡稱爲LIFO線性表。
Stack.h
#pragma once template <class T> class Stack { public: Stack() //構造函數 :_arr(NULL) , _top(0) , _capacity(0) {} ~Stack() //析構函數 { if (_arr) { delete[] _arr; } } public: void Push(const T& x) //插入 { _CheckCapacity(); _arr[_top++] = x; } void Pop() //刪除 { assert(_top > 0); --_top; } size_t Size() //大小 { return _top; } bool Empty() //判斷棧是否爲空 { //return _top == 0; if (_top <= 0) { return true; } else return false; } T& Top() //獲取棧頂元素 { return _arr[_top - 1]; } protected: void _CheckCapacity() { if (_arr == NULL) { _capacity = 5; _arr = new T[_capacity]; return; } else if (_top == _capacity) { _capacity *= 2; T* tmp = new T[_capacity]; for (size_t i = 0;i < _top;++i) { tmp[i] = _arr[i]; } delete[] _arr; _arr = tmp; } } protected: T* _arr; size_t _top; size_t _capacity; }; void TestStack() //測試用例 { Stack<char> s; s.Push('a'); s.Push('b'); s.Push('c'); s.Push('d'); while (!s.Empty()) { cout << s.Top() << " "; s.Pop(); } cout << endl; }
隊列的定義
隊列簡稱隊,它也是一種運算受限的線性表,其限制僅允許在表的一端進行插入,而在表的另一端進行刪除。
把進行插入操作的一端稱爲隊尾(rear),進行刪除操作的一端稱爲隊首或隊頭(front)。
向隊列中插入新元素稱爲進隊或入隊,新元素入隊後就成爲新的隊尾元素;從隊列 中刪除元素稱爲出隊或離隊,元素出隊後,其後繼元素就成爲隊首元素。
隊的特殊性在於插入只能在表的一端進行(只進不出),而刪除只能在表的另一端進行(只出不進),所以隊列的操作原則是先進先出,又稱作FIFO表(First In First Out)。
Queue.h
#pragma once template <class T> struct Node { T _data; Node<T>* _next; Node(const T& x) :_data(x) ,_next(NULL) {} }; template <class T> class Queue { public: Queue() :_head(NULL) ,_tail(NULL) ,_size(0) {} ~Queue() { if (_head) { delete _head; } } public: void Push(const T& x) //在隊尾插入數據 { if (_head == NULL) //隊列爲空的情況 { _head = _tail = new Node<T>(x); } else { _tail->_next = new Node<T>(x); _tail = _tail->_next; } ++_size; } void Pop() //在隊頭刪除數據 { assert(_head); if (_head == _tail) //隊列只有一個數據的情況 { delete _head; _head = _tail = NULL; } else { Node<T>* tmp = _head; _head = _head->_next; delete tmp; } --_size; } bool Empty() { return _head == NULL; } size_t Size() { return _size; } T& GetFront() //獲取隊頭數據 { assert(_head); return _head->_data; } T& GetTail() //獲取隊尾數據 { assert(_tail); return _tail->_data; } protected: Node<T>* _head; Node<T>* _tail; size_t _size; }; void TestQueue() //測試用例 { Queue<int> q; q.Push(1); q.Push(2); q.Push(3); q.Push(4); while (!q.Empty()) { cout << q.GetFront() << " "; q.Pop(); } cout << endl; }