You are on page 1of 5

CA-3

CAP-282
12113647
Kiran Pilania

Write a program to search for a specific element in a given stack using


linked list representation

#include <iostream>
#include <stdlib.h>
#include <malloc.h>
using namespace std;

void push(int);
void pop();
void display();
void search(int);

struct node
{
int data;
struct node *next;
} *head = NULL;

int main()
{
int choice, num, search_num;
while (true)
{
cout << ".....MENU....." << endl;
cout << "1. Push" << endl;
cout << "2. Pop" << endl;
cout << "3. Display" << endl;
cout << "4. Search" << endl;

cout << "Enter your choice: " << endl;


cin >> choice;
cout << endl;
switch (choice)
{
case 1:
cout << "Enter data: ";
cin >> num;
push(num);
break;
case 2:
pop();
break;
case 3:
display();
break;
case 4:
cout << "Enter number to search from the stack : ";
cin >> search_num;
search(search_num);
break;
default:
cout << "Please enter valid option." << endl;
}
}
return 0;
};
void search(int num)
{
struct node *temp;
temp = head;
while (temp->next != NULL)
{
if (num = temp->data)
{
cout << "element found in the list";
return;
}
temp = temp->next;
}
}

void push(int num)


{
struct node *temp;
temp = (struct node *)malloc(sizeof(struct node));
temp->data = num;
if (head == NULL)
{
temp->next = NULL;
head = temp;
}
else
{
temp->next = head;
head = temp;
}
};
void pop()
{
struct node *r;
r = head;
if (r == NULL)
{
cout << "Stack is empty, deletion not possible." << endl;
return;
}
else
{
head = r->next;
free(r);
}
};

void display()
{
struct node *r;
r = head;
if (r == NULL)
{
cout << "Stack is empty" << endl;
return;
}
else
{
while (r != NULL)
{
cout << r->data << " ";
r = r->next;
}
}
cout << "\n\n";
};

You might also like