50 likes | 241 Views
STACK (Linear Stack) Traverse i.e. Printing all the elements of an Stack. A[4]. Traverse means printing all elements of stack. A[3]. If we have to print more than one element , than we have to use Loop. A[2]. A[1]. If stack is empty , then no element is to be printed out. A[0].
E N D
STACK (Linear Stack) Traverse i.e. Printing all the elements of an Stack A[4] Traverse means printing all elements of stack A[3] If we have to print more than one element , than we have to use Loop A[2] A[1] If stack is empty , then no element is to be printed out A[0] if top = -1 then stack is empty top= -1
STACK (Linear Stack) Traverse Suppose 3 elements are available A[4] So , value of top is 2 A[3] Coding of Traversing 30 top= 2 A[2] cout<<A[TOP]; 20 A[1] top= 1 TOP--; 10 top= 0 A[0] cout<<A[TOP]; top= -1 TOP--; Now, we cannot print an element Stack is empty cout<<A[TOP]; TOP--; Value of top =-1
Coding of Traversing an element in stack Traverse Operation is called as :Traverse() Important Point: Before traversing stack , we have to check whether the stack is empty or not Stack is empty: if top = -1 If Stack is not empty, cout<<A[top]; Top---; This process continues until top becomes -1
Coding of Traverse() void Traverse() { if(top==-1) cout<<“Underflow or empty”; else { cout<<“Elements of stack are: “<<endl; while(top>=0) { cout<<a[top]; top---; } } }
Wow !!!! Traverse • Easy…very Easy Foolish thing , we did. Question was : To traverse an array. But Not Delete Top -- means “Deleting an element”