[Data Structures] Can stack be searched or traversed?

Nue

...
Assuming that the stack is implemented using array , is it okay to search or traverse the stack without actually popping the contents? I mean, wouldn't it defeat the purpose of stack itself since stack is a restricted data structure? Need to clear some doubts so I'll be very much obliged if someone helps me out. :)
 
It depends on the context and purpose of creating the stack. Suppose you maintained a stack of people. Now you need to look if a particular perso is present in the stack or not. In this case, you may traverse the stack just like an aray without using pop operation. If such traversal causes a disruption in the LIFO behavior in the purpose of stack creation, then such traversal must be avoided.

if LIFO rule is to be followed strictly, then you may pop the elements from one stack and push them into another stack. tihs way you'll be getting access to every element of the stack and will be following the concepts of stack too. To restore the original state of stack, pop back from the new stack and push into the original stack.
 

deepakkrishnan

Broken In
One can perform the following operations on any data structure

1.Traversing
2. Inserting
3. Deletion
4. Searching
5. Sorting

You can implement them using any one of the Linear data structures mentioned below
1. Array
2. List
3. Trees (if you're feeling adventurous)

Now it does look like that you know the basics of "Stack", ie. Last-In First-Out (LIFO).

And the answer to your question Yes, it would defeat the purpose of stack of you do not use Push or Pop. One has to implement Push & Pop to access (Check or Read ) the element. If you don't use those then it would behave like a normal array or linked list
 
OP
N

Nue

...
Thank you for the replies. Appreciate it :)

My understanding was that you can perform only push and pop operation on the stack but today we were asked to write a function that would search for a given element in the stack and return it if it exists. This left me confused :evil:

Wouldn't stack be usually implemented when the LIFO order must be strictly followed? Assuming that's the case, if I want to search the stack for a particular element, the best practice would be to pop the contents until the desired element is found and then push them back onto the stack in their original order, correct? And if I do that, wouldn't it be more convenient to store the popped elements in a separate array since having two stacks would get kind of redundant? Or am I missing something here? :-?
Also, is there a data structure generally preferred for implementing stack or is it just a matter of one's preference?
 

vickybat

I am the night...I am...
Thank you for the replies. Appreciate it :)

My understanding was that you can perform only push and pop operation on the stack but today we were asked to write a function that would search for a given element in the stack and return it if it exists. This left me confused :evil:

Wouldn't stack be usually implemented when the LIFO order must be strictly followed? Assuming that's the case, if I want to search the stack for a particular element, the best practice would be to pop the contents until the desired element is found and then push them back onto the stack in their original order, correct? And if I do that, wouldn't it be more convenient to store the popped elements in a separate array since having two stacks would get kind of redundant? Or am I missing something here? :-?
Also, is there a data structure generally preferred for implementing stack or is it just a matter of one's preference?

You are getting confused between different data structures mate. Stack is based on Last-In-First-Out concept, i.e the last element pushed is the first element popped. I'll give you a simple analogy.

Consider a courier service where you are assigned to process and acknowledge different documents received. You have a placeholder container at your side where new letters and documents are dumped for you to process. The first letter arrives, then next and next, until the newest letter is always at top. Now in a stack, you will always pick the newest or top-most letter to process. After that, you remove it (pop) and process the next letter on top. So the first letter that had arrived will be processed at last, and all new letters will be on top, getting first priority.

If you want to process the first letter, i.e at the bottom, then you following a "Queue" and not a "Stack". Queue follows the first in first out mechanism. If you want to prioritize the letters by traversing the pile and choosing which letter to process first, then it becomes a "Priority Queue".

Stack is designed to follow LIFO. As a programmer, you cannot traverse the array, or else it won't be a stack. It will be a priority queue or something else. Most microprocessors are designed towards a stack implementation, i.e newest threads that are pushed into the memory are the first ones to be processed and popped for write back.

Consider the following example of a stack. I've implemented this in JAVA, while you can prefer you own programming language. There are no array traversing code in a stack, else it won't be called as one.

PHP:
 //Mechanism of Stack data structure implemented in JAVA

public class newStack {
	
	private int[] testArr ;
	private int size;
	private int first ;
	
	public newStack(int s) {
		
		size = s;
		testArr = new int [size];
		first = -1;
	}
	
 public void push(int m) {
	 
	   testArr[++first] = m;
	 
 }
 
 public int pop (){
	 
	   return testArr[first--];
	 
 }
 
 public int peek() {
	
	   return testArr[first];
	 
 }
 
 public boolean isEmpty(){
	 
	   return (first == -1);
 }
 
 public boolean isFull(){
	 
       return (first == size - 1);
 
 }

}

PHP:
// Test Code of stack implementation

import java.util.Scanner;

public class StackTest {

	public static void main (String args []){
		
		newStack stack = new newStack(10);
		Scanner in = new Scanner(System.in);
		
		System.out.println("Enter the desired values max upto arraysize:");
		while (!stack.isFull()){
			
	         stack.push(in.nextInt());
		     
		}
		while(!stack.isEmpty()){
			
		 int n = stack.pop();
		 
		 System.out.print(n);
		 System.out.print(" ");
		 
	    }
		System.out.println("");
		
	}
}

If you are a C++ programmer, you will able to understand this. Test it out on an Eclipse or Netbeans IDE or any java compiler. It will ask you keyboard input and you can understand how a stack and its LIFO mechanism works. :)
 
OP
N

Nue

...
@vickybat:
Thank you for the reply.
I apologize if it looked like I was confused but I'm quite clear about the LIFO structure. That's the reason I asked if we can search the stack like a normal array.

This is what I've done so far. Not a complete program but mainly to show how the stack would be searched.
PHP:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

#define STACK_SIZE 10

int contents[STACK_SIZE];
int top;

void init( void ); // Initializes the stack.
bool isEmpty( void ); // Returns true if the stack is empty.
bool isFull( void ); // Returns true if the stack is full.
void Push( int i ); // Pushes an element onto the stack.
int Pop( void ); // Pops an element off the stack.
bool search( int ); // Searches the stack for a given element and returns true if it exists.

int main(int argc, char const *argv[])
{
    int i, key;
    
    // Create a stack
    init();
	
	// Populate the stack with a few elements
	for (i = 0; i < STACK_SIZE; i++)
        Push(i);
    
    printf("Enter element to search: \n");
    scanf("%d", &key);
	
	if (!search(key))
		printf("Element not found"); // search returned false.
	else
		printf("Element found"); // searched returned true.
	

	fflush(stdin);
	getchar();
	return 0;
}

void init( void )
{
    top = 0;
}

bool isEmpty( void )
{
	return top == 0;
}

bool isFull( void )
{
	return top == STACK_SIZE;
}

void Push( int val )
{
	if ( isFull() ) {
		printf("Stack Overflow\n");
		exit(1);
	}
	contents[top++] = val;
}

int Pop( void )
{
	if ( isEmpty() ) {
		printf("Stack underflow\n");
		exit(1);
	}
	return contents[--top];
}

bool search( int key )
{
    if ( isEmpty() ) {
		printf("Stack is Empty\n");
		exit (1);	
	}
	
	while ( !isEmpty() ) {
		if (Pop() == key)
			return true; 
    }

    return  false;
}
 
^ that search function is actually destroying the stack. Everytime you call Pop(); an element from the stack is deleted by decrementing the top pointer. If you have to follow the principles of LIFO strictly, you can create a similar sized stack and instead of just popping elements, push the popped elements into the temporary stack. Once the search code is done, push all the popped elements from temporary stack into original stack.
 
OP
N

Nue

...
Here's the new search function. I stored the popped contents in a separate array instead of creating another stack.
PHP:
bool search( int key )
{
    int found = false;
    int count = 0;
    int temp[STACK_SIZE];
    if ( isEmpty() ) {
		printf("Stack is Empty\n");
		exit (1);	
	}
	
    while ( !isEmpty() ) {
		if ( (temp[count++] = Pop()) == key) {
			found = true;
			break;
		}
    }

    while ( !isFull() )
    	Push(temp[--count]);

    return  found;
}
 

vickybat

I am the night...I am...
@vickybat:
Thank you for the reply.
I apologize if it looked like I was confused but I'm quite clear about the LIFO structure. That's the reason I asked if we can search the stack like a normal array.

This is what I've done so far. Not a complete program but mainly to show how the stack would be searched.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

#define STACK_SIZE 10

int contents[STACK_SIZE];
int top;

void init( void ); // Initializes the stack.
bool isEmpty( void ); // Returns true if the stack is empty.
bool isFull( void ); // Returns true if the stack is full.
void Push( int i ); // Pushes an element onto the stack.
int Pop( void ); // Pops an element off the stack.
bool search( int ); // Searches the stack for a given element and returns true if it exists.

int main(int argc, char const *argv[])
{
    int i, key;
    
    // Create a stack
    init();
	
	// Populate the stack with a few elements
	for (i = 0; i < STACK_SIZE; i++)
        Push(i);
    
    printf("Enter element to search: \n");
    scanf("%d", &key);
	
	if (!search(key))
		printf("Element not found"); // search returned false.
	else
		printf("Element found"); // searched returned true.
	

	fflush(stdin);
	getchar();
	return 0;
}

void init( void )
{
    top = 0;
}

bool isEmpty( void )
{
	return top == 0;
}

bool isFull( void )
{
	return top == [B][SIZE=4]STACK_SIZE - 1[/SIZE][/B];
}

void Push( int val )
{
	if ( isFull() ) {
		printf("Stack Overflow\n");
		exit(1);
	}
	[B][SIZE=4]contents[++top] = val[/SIZE];[/B]
}

int Pop( void )
{
	if ( isEmpty() ) {
		printf("Stack underflow\n");
		exit(1);
	}
	[B][SIZE=4]return contents[top--][/SIZE];[/B]
}

bool search( int key )
{
    if ( isEmpty() ) {
		printf("Stack is Empty\n");
		exit (1);	
	}
	
	while ( !isEmpty() ) {
		if (Pop() == key)
			return true; 
    }

    return  false;
}

Slightly fixed the push and pop methods. :)

In push(), the top is incremented first and then a value is assigned.

In pop, the top is simply decremented. The underflow check condition is good.

Now coming to the main part, the search function is kind of unnecessary in a stack. I don't know why your teacher is encouraging you to even try it.
I mean what's the point really?

Suppose you have the required key at "n" index, you have to pop each and every element out of the stack upto "n" element, in order for a match.
So you are doing n pops basically. If the nth value is big i.e 100 or more, then you've to do 100 pops or more to find the key. Its simple linear search and is inefficient.

Stacks are never designed for any searching purpose.

If you want efficient search algorithm, try binary search. Also ask your teacher why they are encouraging to search a key from a stack.
You can use stacks for more practical purposes like reversing a string. Notice what happens when you pop elements out of a stack. Aren't the order reversed?
 
OP
N

Nue

...
Slightly fixed the push and pop methods. :)

In push(), the top is incremented first and then a value is assigned.

In pop, the top is simply decremented. The underflow check condition is good.

Now coming to the main part, the search function is kind of unnecessary in a stack. I don't know why your teacher is encouraging you to even try it.
I mean what's the point really?

Suppose you have the required key at "n" index, you have to pop each and every element out of the stack upto "n" element, in order for a match.
So you are doing n pops basically. If the nth value is big i.e 100 or more, then you've to do 100 pops or more to find the key. Its simple linear search and is inefficient.

Stacks are never designed for any searching purpose.

If you want efficient search algorithm, try binary search. Also ask your teacher why they are encouraging to search a key from a stack.
You can use stacks for more practical purposes like reversing a string. Notice what happens when you pop elements out of a stack. Aren't the order reversed?
Exactly. Why would you want to search a stack? And in fact, I did ask my teacher that question. She just gave me the look and said it's fine if you have to do it, there's nothing wrong with it. Well, whatever. For now, I'll just do it with the function I posted in post #8 which maintains the LIFO structure.
Thank you all for the help.
 
Top Bottom