Implement a linear search using the stack data structureSolu

Implement a linear search using the stack data structure.

Solution

I have inserted 5 items and searched for one number i.e 9. You can change the same for search.

#include<stdio.h>
#include<conio.h>
#include<iostream.h>

class Stack
{
int top;
public:
int a[10];
Stack()
{
top = -1;
}
int Stack::getsize();
void Stack::push(int x);
int Stack::pop();
void Stack::isEmpty();
bool Stack::linearsearch1(int p);
  
};

int Stack::getsize()
{
return top+1;
}
void Stack::push(int x)
{
if( top >= 10)
{
cout << \"Stack Overflow\ \";
}
else
{
a[++top] = x;
cout << \"Element Inserted\ \";
}
}

int Stack::pop()
{
if(top < 0)
{
cout << \"Stack Underflow\ \";
return 0;
}
else
{
int d = a[top--];
return d;
}
}
void Stack::isEmpty()
{
if(top < 0)
{
cout << \"Stack is empty\";
}
else
{
cout << \"Stack is not empty\";
}
}

bool Stack::linearsearch1(int p)
{
bool f=false;
int x;
int n=getsize();
for (int i=0;i<n;i++)
{
x=pop();
if(x==p)
{
f=true;
break;
}
}
return f;

}
int main()
{

Stack s;
s.push(5);
s.push(7);
s.push(9);
s.push(16);
s.push(12);
if(s.linearsearch1(9))               //Change the number which you want to search
cout<<\"Item Found\"<<endl;
else
cout<<\"Not Found\"<<endl;
}

Implement a linear search using the stack data structure.SolutionI have inserted 5 items and searched for one number i.e 9. You can change the same for search.
Implement a linear search using the stack data structure.SolutionI have inserted 5 items and searched for one number i.e 9. You can change the same for search.

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site