Stack Representation
Stack Representation
A stack is an Abstract Data Type (ADT), commonly used in most programming languages.
A stack in real life is a deck of cards or a pile of plates which allows operations at one end
only.
Stack Representation
The following diagram depicts a stack and its operations −
A stack can be implemented by means of Array, Structure, Pointer, and Linked List. Stack
can either be a fixed size one or it may have a sense of dynamic resizing. However for the
purpose of discussion an array will be used, which makes it a fixed size stack
implementation.
Basic Operations
Push Operation
The process of putting a new data element onto stack is known as a Push Operation. Push
operation involves a series of steps −
● Step 1 − Checks if the stack is
full.
● Step 2 − If the stack is full,
produces an error and exit.
● Step 3 − If the stack is not full,
increments top to point next
empty space.
● Step 4 − Adds data element to
the stack location, where top is
pointing.
● Step 5 − Returns success.
Pop Operation
Accessing the content while removing it from the stack, is known as a Pop Operation. In an
array implementation of pop() operation, the data element is not actually removed, instead
top is decremented to a lower position in the stack to point to the next value. A Pop
operation may involve the following steps −
● Step 1 − Checks if the stack is
empty.
● Step 2 − If the stack is empty,
produces an error and exit.
● Step 3 − If the stack is not empty,
accesses the data element at
which top is pointing.
● Step 4 − Decreases the value of
top by 1.
● Step 5 − Returns success.
Applications
Reverse a string
Algorithm:
1. Create an empty stack.
2. One by one push all characters of string to stack.
3. One by one pop all characters from stack and put them back to string.
Simulation:
Input Text: reverse
2. push( r )
3. r push( e )
4. r e push( v )
5. r e v push( e )
6. r e v e push( r )
7. r e v e r push( s )
8. r e v e r s push( e )
Infix to Postfix
Infix expression:
Simulation:
Note:
Consider each operand as a single character;
* and / has the same precedence;
+ and - has the same precedence;
* and / has a higher precedence than + and -.
Input Text: 1 + 2 * 3
2. Read 1 Output: 1
3. + Read + push(+)
4. + Read 2 Output: 1 2
5. + * Read * push(*) p
recedence over +
6. + * Read 3 Output: 1 2 3