Data Structure: Stack implementation in C++

The more detailed explanations can be found here.

(A) Top of stack varying method
Algorithm for top of stack varying method

1. Declare and initialize necessary variables, eg top = -1, MAXSIZE etc.
2. For push operation,
If top = MAXSIZE – 1
print ” stack overflow”
else
top = top + 1;
Read item from user
stack[top] = item
3. For next push operation, goto step 2.
4. For pop operation,
If top = -1
print “Stack underflow”
Else
item = stack[top]
top = top – 1
Display item
5. For next pop operation, goto step 4.
6. stop

Source code for top of stack varying method

(B) Top Fixed method ( Base varying method)

Algorithm for top fixed method

1. Declare and initialize necessary variables e.g. BOS = 0, MAXSIZE etc.
2. For push operation,
If BOS = MAXSIZE
print “stack overflow”
Else
Insert new element by making vacant space at stack[0] location
/* for(i = BOS; i > 0; i–){
stack[i] = stack[i-1];
}
stack[0] = BOS
++BOS
*/
3. For next push operation goto step 2.
4. For pop operation
If BOS = 0
print”stack underflow”
else
extract item from stack[0]. Decrement BOS and refil empty space by lowering each step by 1.
5. For next pop operation, goto step 4.
6. Stop

 

Source code for top fixed method

SHARE Data Structure: Stack implementation in C++

You may also like...

3 Responses

  1. Implementation in C++
    Algorithm for PUSH Operation:
    Step 1: If TOP >= SIZE – 1 then
    Write “Stack is Overflow”
    Step 2: TOP = TOP + 1
    Step 3: STACK [TOP] = X
    Algorithm for POP Operation:
    Step 1: If TOP = -1 then
    Write “Stack is Underflow”
    Step 2: Return STACK [TOP]
    Step 3: TOP = TOP – 1

  2. If any error in this code segment

    If(top<size) then
    Top=top+1
    Stack[top]=can
    Else
    Print "stack over flow"
    End of if

Leave a Reply

Your email address will not be published. Required fields are marked *

Share