Use app×
Join Bloom Tuition
One on One Online Tuition
JEE MAIN 2025 Foundation Course
NEET 2025 Foundation Course
CLASS 12 FOUNDATION COURSE
CLASS 10 FOUNDATION COURSE
CLASS 9 FOUNDATION COURSE
CLASS 8 FOUNDATION COURSE
0 votes
9.9k views
in Computer by (61.3k points)

Write an algorithm that depending upon user’s choice, either pushes or pops an elements in a stack implemented as an array. (The elements are shifted towards right to combine all free spaces in the left)

1 Answer

+1 vote
by (64.2k points)
selected by
 
Best answer

Algorithm for user choice: 

1.  ch=0 // Initialize a variable for user choice 

2.  Read ch //Enter, user choice 1 for push and 2 for pop

3.  If(ch == 1) then /* if top is at end of stack-array */

4.  call push function

5.  Else

6.  call pop function

7.  End 

Algorithm for pushing in stack-array:

* Assuming that array-stack can hold maximum N elements*/ 

1.  top=-1 /* Initialize stack with invalid subscript value to show that it is empty. Legal subscript values are 0..... (N-1) */

2.  Read Item //Item, which is to be pushed

3.  If(top== N-1) then /* if top is at end of stack-array */

4.  { print "Overflow !!"

}

5.  Else

6.  { top = top+1 /* Increment top to move to next empty position to hold new item*/

7.  Stack[top]=Item }

8.  END.

Algorithm for popping in stack-array: 

/* Firstly, check for underflow condition */ 

1.  If top==-1 then

2.  Print "Underflow!!"

3.  Exit from program

}

4.  Else

{

5.  print stack(top)

6.  top=top-1 /* top moved, so that the top most element becomes inaccessible which is a sort of a deletion */ }

7.  END

Note: We have to shift elements to the right for insertion and left for removal of an element. We face the same problem while implementing the list with the use of the array. If we push and pop the elements from the start of the array for stack implementation, this problem will arise. In case of push, we have to shift the stack elements to the right. However, in case of pop, after removing the element, we have to shift the elements of stack that are in the array to the left. If we push the element at the end of the array, there is no need to shift any element. Similarly as the pop method removes the last element of the stack which is at the end of the array, no element is shifted. To insert and remove elements at the end of the array we need not to shift its elements. Best case for insert and delete is at the end of the array where there is no need to shift any element. We should implement push() and pop() by inserting and deleting at the end of an array.

Welcome to Sarthaks eConnect: A unique platform where students can interact with teachers/experts/students to get solutions to their queries. Students (upto class 10+2) preparing for All Government Exams, CBSE Board Exam, ICSE Board Exam, State Board Exam, JEE (Mains+Advance) and NEET can ask questions from any subject and get quick answers by subject teachers/ experts/mentors/students.

Categories

...