- The definition of stack--stack
Stacks are linear tables that are only allowed to be inserted and deleted at the end. The stack has a LIFO attribute (LIFO, last in Fast out).
People who have studied data structures know that stacks can be implemented in two ways, one is to implement stacks with arrays, and this stack becomes static, and the other is to implement stacks with linked lists, which are called dynamic stacks.
- Implementation of the Stack
Below is the source code (sequential table) of a stack structure implemented in C + +
1 #pragmaOnce2#include <iostream>3#include <assert.h>4 using namespacestd;5Template<typename t>6 classStack7 {8 Public:9 Stack ()Ten : Array (NULL) One, Size (0) A, Capacity (0) - {} -~Stack () the { - if(Array! =NULL) - { - Delete[] array; + } -Capacity =0; +Size =0; A } atStack (Conststack<t>&s) - { -Array =NewT[s.size]; -memcpy (Array, S.array,sizeof(T) *s.size); -Size =s.size; -Capacity =s.capacity; in } -stack<t>&operator=(Conststack<t>&s) to { +Capacity =s.capacity; -Size =s.size; the This->array =S.array; * return* This; $ }Panax Notoginseng voidPrint () - { the for(intindex =0; index < size; index++) + { Acout << Array[index] <<" "; the } +cout <<Endl; - } $ voidPush (Constt&x) $ { - _checkcapacity (); - thearray[size++] =x; - }Wuyi the voidPop () - { WuASSERT (Size >0); ---size; About } $ - size_t size () - { - returnsize; A } + the BOOLEmpty () - { $ returnSize = =0; the } the the Constt&Top () the { -ASSERT (Size >0); in the returnArray[size-1]; the } About protected: the void_checkcapacity () the { the if(Size >=capacity) + { -T *temp =NewT[capacity *2+3]; the for(intindex =0; index < size; index++)Bayi { theTemp[index] =Array[index]; the } - Delete[] array; -Array =temp; theCapacity = capacity *2+3; the } the the } - the protected: theS MArray; the size_t size;94 size_t capacity; the }; the voidFun () the {98stack<int>s; AboutS.push (6); -S.push (7);101S.push (8);102S.push (9);103 s.print ();104cout << s.top () <<" "; the S.pop ();106 }107 voidMain ()108 {109 Fun (); theSystem"Pause");111}
Stacks (Stack)