C ++: simple stack implementation using sequence tables

Source: Internet
Author: User

C ++: simple stack implementation using sequence tables

Main. cpp # include <iostream> # include <string> # include "Stack. hpp "using namespace std; void test1 () {// test Stack <int> s1; s1.Push (1); s1.Push (2); s1.Push (3); s1.Push (4 ); s1.Pop (); s1.Pop (); s1.Pop (); s1.Pop ();} int main () {test1 (); return 0;} Stack. hpp # pragma oncetemplate <class T> // you can use a template to implement multiple types of Stack operations class Stack {private: T * _ array; // data structure size_t _ capacity; // number of incoming stacks int _ topindex; // empty Stack/full judgment standard public: Stack (): _ array (0), _ capacity (0 ), _ topindex (-1) {} void Push (const T & x) {// inbound stack if (_ topindex + 1 = _ capacity) {// determine whether to open up space _ capacity = 2 * _ capacity + 3; T * tmp = new T (_ capacity); if (tmp = NULL) {cout <"failed new" <endl; exit (-1);} memcpy (tmp, _ array, sizeof (T) * (_ topindex + 1 )); // use delete _ array for built-in types; // memcpy, custom _ array = tmp; // use the for loop to copy one by one} // note the deep copy and pre-copy _ array [++ _ topindex] = x;} void Pop () {// out-of-stack if (_ topindex>-1) {cout <_ array [_ topindex] <endl; _ topindex -- ;}} bool empty () {// clear stack return _ topindex =-1 ;}};

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.