Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 6

Can i convert recursion to iterative approach?

programmer stack

using loops==>recursion takes=>stack memory

ADT of stack(abstract data type)=>

1.it contains the data represntation & operation on stack.

ADT stack

(Data representation)

1.Data

2.space for storing the collection of elements.

3.Top pointer-->point on the top of the stack==(-1)

Operations:

1.push()

2.pop()

3.peek(index)

4.stackTop()

5.isEmpty()

6.isFull()

1.push()==>insertion of elements can be done using push

2.pop()==>deleteion or retrival of elements can be done using pop

3.Peek()==>by looking at value , it will give the index of that place.

4.stackTop()==>it fetch the topmost value in the stack.

5.isEmpty()==>to check whether stack is empty or not

6.isFull==>to check whether stack is full or not.

How we can perform the implementation of stack?

(LIFO)==>Last in first out


Where do we store the collection of elements?

1.Array

2.Linked list

How to implement Stack using Arrays?

1. We need a fixed size array.We have created an array of size 6.

2. size =6

3.We need a top pointer that points on the most elements.

data type[int].

4. top should be of integer type . it is pointing on the index which is recently

inserted elements.

5.How many things we require to imple. stack?

3.

1 SIZE

2. Top

3. Array

//Defining a structure of stack

struct stack{

int size;

int top;

int *s;==>pointer to an array.

How to initialize an stack?

int main(){

struct stack st;//created an object st for sturct stack


pf("Size");

scanf("%d",&st.size);

st.s= new int[st.size];

//TOP

3. Where Top should point?

The top should be before 0

initialize the top as -1

st.top=-1;

HoW we perform the operation on the stack?

1.When we say stack is empty?

2. what will condition?

3. When stack is Full?

-1==>top

if(top==-1)//stack is empty==>underflow

if(top==size-1)// stack is full==>overflow

Operation on stack push and pop==>

1.initally top is pointing to -1. there is no elements in the stack

2.Increment top pointer.

top++ or top=top+1

s[top]=

3.Once all the elements are inserted till array size. i can not insert more

elements[Overflow condition]

6.pop()==>top-- or top=top-1;
function for push

void push(stack *st,int x)

if(st->top==size-1)

pf("Overflow"); //can not insert more elements

else

st->top++;

st->S[st->top]=x;

Function for pop operation

int pop(stack *st)

int x=-1;

if(st->top==-1)

pf("Stack underflow");

else

x=st->s[st->top];

st->top--;//decrement top pointer


}

return x;

Peek()==>

postion index

1 3

2 2

3 1

4 0

index by using formula ==>Top-position+1=index

int peek(stack st, int pos)

int x=-1;

//check position is valid or not

if(top-pos+1<0)

pf("Inavlid position");

else

x=st.s[st.top-pos+1];

return x;

Time complexity==>

You might also like