Saturday, December 10, 2011

Data Structures: Stack

Data Structures can be defined as arrangement and storage or organization of data so that inserting, retrieving and modifying the data becomes efficient, faster and easier. There are different kinds of data structures available and can be used in our applications according to our requirement. Any application we develop is all about manipulating the data. So data structures are always required to write any application. Any data structure we consider can be implemented in any language of your choice. Hence data structures are independent of language. Data Structure consists of two parts:
  1. Data.
  2. Operations on that data.

We all know about the data. What are operations? Any data structure will commonly give insert, read, update and delete operations. In addition to these operations specific functions can be written for that data structure like if we consider List we can have sort() functionality in addition to the above functionality. As Data Structures are important of the application development, I have decided to write all the data structures that I know on my blog. To start with the simplest one Stack.
STACK: Stack can be defined as LIFO kind of data structure i.e last in first out. I remember an example which my professor gave us. In mess, the plates in which we are served food are all kept piled one upon another. Stack is same as that pile of plates. The plate which was put first on table will be the last to be served and last becomes first to be served. Stack is very restricted data structure. It has only two operations push() and pop(). Push is used to put any data into the stack. It is equivalent to arranging the plates. Pop is used to retrieve the data back from the stack. It is equivalent to serving the food to people. Stack can be graphically can be imagined as:
In the stack shown above. Element in colour red was first to be inserted and element in navy blue was the last element inserted. Now if I call push() operation on above stack element with orange colour will be inserted above fourth element as shown.
Now if i call pop() operation on above stack last inserted element i.e. orange element will be removed from the stack getting us back to the previous stack.
Stack is used to manage memory of the program during runtime. When a sub-routine is called current state of memory is saved into the stack which corresponds to the push operation. when sub-routine execution finishes, pop() operation is called to get the previous state of the program.
This brings us to the end of stack data structure. Please write in your comments and any queries. In the next post, I ll be explaining another data structure Link List. Thank you.

No comments:

Post a Comment