You are here:

C/Doubt on implementing stack using array!!

Advertisement


Question
How can STACK be implemented using array??
coz array is static memory allocation unit.
so when we POP any element frm stack it cannot be deleted frm memory...
Plz help me.....

Answer
A stack is merely a data structure concept.  The only rules that must be followed when implementing a stack is that data must be first-in-last-out.  Often times, stacks are implemented with dynamic memory and pointers, but can be just as easily implemented with an array.  

Essentially, you must simply maintain the index of the current top of the stack.  To push an item onto the stack, you simply assign your new item to the current top.  To pop an item off of the stack, you simply return the current top item and decrement your top index.  Something like:

   void push(int _item)
   {
       stack[topIndex++] = _item;
   }

   int pop()
   {
       return stack[--topIndex];
   }

In the above implementation, the topIndex value always points to the current "empty" index in the array.  It will initialize to 0 with an empty stack array.  Also, note that I'm not doing any error checking in those functions.  You should make sure that your index never goes out of bounds and error appropriately if it does.  This is just a brief synopsis of how this would be implemented.  In this implementation, the last item pushed onto the stack will always be at topIndex - 1.

C

All Answers


Answers by Expert:


Ask Experts

Volunteer


Joseph Moore

Expertise

I've been programming in one form or another since my brother taught me BASIC when I was 6. I've been programing professionally since I was 20, first web development with HTML, JS, DHTML, CSS, etc., then I became a video game developer, writing code in C, C++, C#, SQL, assembly, and various scripting languages. I've even written my own scripting languages, custom designed for the games I was making. I also dabble in Java, PHP, and Perl. I've worked on pretty much every aspect of game development, including graphics, audio, gameplay, tool, UI, input, animation, and physics.

Experience

I've been writing C code for 12 years, both on my own in my spare time and professionally.

Organizations
IGDA

Education/Credentials
Bachelor of Science in Game Design and Development, Full Sail University, Winter Park, FL

Awards and Honors
Salutatorian and Advanced Achiever Awards at Full Sail; Independent Games Festival Student Showcase winner, 2004; Featured article on Gamasutra about an experimental game developed in 2004

©2012 About.com, a part of The New York Times Company. All rights reserved.