C + + chain stack implementation __c++

Source: Internet
Author: User

Chain Stack is implemented with a linked list, it is stored in memory is not continuous , and the number of nodes stored is variable, can be inserted or deleted according to the actual situation. This makes it more reasonable to take advantage of memory resources, making programs more flexible and less memory overhead.

The difference between a chain stack and a linked list is:

(1) Chain stack without head node, linked list in order to unify the empty table and non-empty table operation to join the head node

(2) Chain stack without head pointer and tail pointer

(3) The elements in the stack are limited, the user can only access the top of the stack


The LinkStack.h file code is as follows:

#include <iostream> using namespace std;
	Template <class t> class Linkstacknode {public:t data;
	Linkstacknode<t>* Next;


Linkstacknode (t& D): Data (d), next (NULL) {}};
	Template <class t> class Linkstack {public:linkstack (): Top (NULL) {} ~linkstack ();
	void push (t& value);
	t& GetTop ();
	T pop ();
BOOL IsEmpty ();
private:linkstacknode<t> * TOP;


};

Template <class t> linkstack<t>::~linkstack () {delete top;} Template <class t> void linkstack<t>::p ush (t& value) {linkstacknode<t>* AddNode = new Linkstacknod
	E<t> (value);
	Addnode->next = top;
top = AddNode;


} template <class t> t& linkstack<t>::gettop () {return top->data;}
	Template <class t> t linkstack<t&gt::p op () {T value = top->data;
	linkstacknode<t>* p = top;
	top = top->next;
	Delete p;
return value; } template <class t> bool Linkstack<t>::isempty () {return top = =NULL; }


The Main.cpp code is as follows:

#include "LinkStack.h"
using namespace std;

int main (int argc, char const *argv[])
{/
	* code */
	linkstack<int> s;
	int i;
	for (i = 0; i < 5; ++i) {
		s.push (i);
	}
	cout << s.gettop () << Endl;
	for (i = 0; i < 3; i++)
	{
		cout << s.pop () << Endl;
	}
	cout << s.gettop () << Endl;
	return 0;
}



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.