Stacks Using C++ Part2
Submitted by moazkhan on Tuesday, August 19, 2014 - 04:01.
Stacks using c++ part2
In this tutorial, you will learn 1. When stacks should be implemented by arrays. 2. When stacks should be implemented by linked list. 3. Implementation of stacks using linked list. When should the stacks be implemented by linked list? In stacks, data is entered and removed from same end. So, there is no insertion and deletion from middle. As we learnt that while inserting data in the middle of an array, this creates a problem. Since in stacks, data is inserted and removed from one end only. So, if we know the number of elements that we have to insert in stack, we can use arrays. Using an array, we can save a lot of space because in case of arrays, you need an array,which takes a single memory space for each element, and a counter. While in case of linked list, you first have to make class of linked list consisting of nodes and each node occupies extra space of a pointer .Thus, by using an array, we can save space. If we don’t know the maximum amount of data we want in our stacks and we want to use arrays, we must build a very large array and this would again require a lot of space . Thus, while using array for implementation of stacks, maximum number of elements must be known. When should the stack be implemented by linked list ? Linked list can be used when the maximum number of elements we can have is unknown . Because linked list is a dynamic type of data structure so it can accommodate any amount of data if used properly. What is the implementation of stacks using linked list?- class Stack
- {
- private:
- linked_list l;
- public:
- Stack(){}
- void push(int value)
- {
- l.insert_beg(value);
- }
- bool Empty()
- {
- if(l. checkempty())
- return 1;
- return 0;
- }
- int get_top()
- {
- if(Empty())
- {
- cout<<"\n\tStack is Empty";
- return 0;
- }
- cout<<"\nTop:\t"<<l.start()->info;
- return l.start()->info;
- }
- int pop()
- {
- if(Empty())
- {
- cout<<"\n\tStack is Empty";
- return 0;
- }
- else
- {
- int c=l.start()->info;
- l.delete_beg();
- return c;
- }
- }
- };
Add new comment
- 117 views