Data Structure (2130702)

BE | Semester-3   Summer-2016 | 06/09/2016

Q2) (b)

Write an algorithm to reverse a string using stack.

1. [Initialize stack]
 TOP <-- 1
 S[TOP] <-- ‘(‘
2. [Initialize output string and rank count ]
 POLISH <-- ‘ ‘
 RANK <-- 0
3. [Get first input symbol]
 NEXT<--NEXTCHAR (INFIX)
4. [Translate the infix expression ]
 Repeat thru step 7 while NEXT != ‘ ‘
5. [Remove symbols with greater precedence from stack]
 IF TOP < 1
 Then write (‘INVALID’)
 EXIT
 Repeat while G (S[TOP]) > F(NEXT)
 TEMP <-- POP (S, TOP)
 POLISH <-- POLISH O TEMP
 RANK <-- RANK + R(TEMP)
 IF RANK <1
 Then write ‘INVALID’)
 EXIT
6. [Are there matching parentheses] IF G(S[TOP]) != F(NEXT)
 Then call PUSH (S,TOP, NEXT)
 Else POP (S,TOP)
7. [Get next symbol]
 NEXT <- NEXTCHAR(INFIX)
8. [Is the expression valid]
 IF TOP != 0 OR RANK != 1
 Then write (‘INVALID ‘)
 Else write (‘VALID ’)