Spread the post

Reverse a string using stack

Write an efficient algorithm to Reverse given string using stack.

Example

Input String : gnimmargorp C

Output String: C programming

Reverse following 2 array data

Stack Areamainarray1 [0] g [1] n [2] i [3] m [4] m [5] a [6] r [7] g [8] o [9] r [10] p [11] [12] C [13] \0array2 [0] e [1] d [2] o [3] c [4] [5] o [6] l [7] l [8] e [9] h [10] \0top(pointer) NULL

Code execution Try it Yourself

Array 1 : After insert array element to stack.

Stack Areamainarray1 [0] g [1] n [2] i [3] m [4] m [5] a [6] r [7] g [8] o [9] r [10] p [11] [12] C [13] \0array2 [0] e [1] d [2] o [3] c [4] [5] o [6] l [7] l [8] e [9] h [10] \0top(pointer)reverse_stringindex (int) =0temp(pointer)top(pointer) Heap Areastruct Stackdata (char)= gnext (pointer)= NULLstruct Stackdata (char)= nnext (pointer) struct Stackdata (char)= inext (pointer) struct Stackdata (char)= mnext (pointer) struct Stackdata (char)= mnext (pointer) struct Stackdata (char)= anext (pointer) struct Stackdata (char)= rnext (pointer) struct Stackdata (char)= gnext (pointer) struct Stackdata (char)= onext (pointer) struct Stackdata (char)= rnext (pointer) struct Stackdata (char)= pnext (pointer) struct Stackdata (char)= next (pointer) struct Stackdata (char)= Cnext (pointer)

After Reverse first array is

Beforearray1 [0] g [1] n [2] i [3] m [4] m [5] a [6] r [7] g [8] o [9] r [10] p [11] [12] C [13] \0 Afterarray1 [0] C [1] [2] p [3] r [4] o [5] g [6] r [7] a [8] m [9] m [10] i [11] n [12] g [13] \0

Function

This function accept two parameters.

1) First index address of string

2) One stack double pointer

This function are perform two stack operation.

1) push : Initial insert all element on stack.

2) pop : Pop stack operation and replace original data string.

Program to reverse string using stack in c. Time complexity O(n).


Output

Stack Areamainarray1 [0] C [1] [2] p [3] r [4] o [5] g [6] r [7] a [8] m [9] m [10] i [11] n [12] g [13] \0array2 [0] e [1] d [2] o [3] c [4] [5] o [6] l [7] l [8] e [9] h [10] \0top(pointer)reverse_stringindex (int) =0temp(pointer)top(pointer)poptop(pointer) Heap Areastruct Stackdata (char)= enext (pointer)= NULLstruct Stackdata (char)= dnext (pointer) struct Stackdata (char)= onext (pointer) struct Stackdata (char)= cnext (pointer) struct Stackdata (char)= next (pointer) struct Stackdata (char)= onext (pointer) struct Stackdata (char)= lnext (pointer) struct Stackdata (char)= lnext (pointer) struct Stackdata (char)= enext (pointer)

Execution Process Try it Yourself

Spread the post

Recommended Posts: