In: Computer Science
Hi I would like to see an example in c++ of Stack As Linked List I need a seek() function which receives a double number X and which returns in which position in the stack is X. If the value X is not in the stack, the function should return -1
Code for the function seek() only:
int seek(double x){
struct Node *ptr;
if(top == NULL)
return -1;//if stack is empty return -1
ptr = top;
int position = 1;//we consider the top position to be the first position
while(ptr != NULL){
if(ptr->data == x)
return position;
else{
ptr = ptr->next;
position++;//update position as we move forward in the list
}
}
return -1;
}
Full working code:
#include <iostream>
using namespace std;
struct Node {//node definition
double data;
struct Node *next;
};
struct Node* top = NULL;
void push(double val) {//pushes the new node
struct Node* newnode = (struct Node*) malloc(sizeof(struct Node));
newnode->data = val;
newnode->next = top;
top = newnode;
}
void pop() {//pops the top element from the stack
if(top==NULL)
cout<<"Stack Underflow"<<endl;
else {
cout<<"The popped element is "<< top->data <<endl;
top = top->next;
}
}
int seek(double x){
struct Node *ptr;
if(top == NULL)
return -1;//if stack is empty return -1
ptr = top;
int position = 1;//we consider the top position to be the first position
while(ptr != NULL){
if(ptr->data == x)
return position;
else{
ptr = ptr->next;
position++;//update position as we move forward in the list
}
}
return -1;
}
void display() {
struct Node* ptr;
if(top==NULL)
cout<<"stack is empty";
else {
ptr = top;
cout<<"Stack elements are: ";
while (ptr != NULL) {
cout<< ptr->data <<" ";
ptr = ptr->next;
}
}
cout<<endl;
}
int main() {
int ch;
double val;
cout<<"1) Push in stack"<<endl;
cout<<"2) Pop from stack"<<endl;
cout<<"3) Display stack"<<endl;
cout<<"4) Seek function"<<endl;
cout<<"5) Exit"<<endl;
do {
cout<<"Enter choice: "<<endl;
cin>>ch;
switch(ch) {
case 1: {
cout<<"Enter value to be pushed:"<<endl;
cin>>val;
push(val);
break;
}
case 2: {
pop();
break;
}
case 3: {
display();
break;
}
case 4: {
cout<<"Enter value : ";
double x;
cin>>x;
int position = seek(x);
cout<<"The postion is "<<position<<endl;
break;
}
case 5: {
cout<<"Exit"<<endl;
break;
}
default: {
cout<<"Invalid Choice"<<endl;
}
}
}while(ch!=5);
return 0;
}
output:
code screenshot: