Open Ended Lab

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 6

Name : Muhammad Bilal

Roll No : FA20-BSE-021

Course Title : Data Structures & Algorithms

Session : 2020-24
Title : Open Ended lab
Mirpur University of Science and
Technology

Doubly Linked list (insertion, traversing and searching)

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

struct Node
{
int data;
struct Node *next;
struct Node *prev;
};
struct Node *first;
void insert(int n)
{
int i, temp; //temp here is for data
struct Node *second;
struct Node *ptr; //this is new node
if (n >= 1)
{
first = (struct Node *)malloc(sizeof(struct Node));

if (first != NULL)
{
cout << "node 1 : ";
scanf("%d", &temp);

first->data = temp;
first->prev = NULL;
first->next = NULL;
}
second = first;
for (i = 2; i <= n; i++)
{
ptr = (struct Node *)malloc(sizeof(struct Node));
if (ptr != NULL)
{
cout << "\nnode " << i << " : ";
scanf("%d", &temp);

ptr->data = temp;
ptr->prev = second; //here i linked new node with previous node
ptr->next = NULL;

second->next = ptr; //here i linked previous node with new node


second = ptr;
}
else
{
cout << "memory cannot be allocated" << endl;
break;
}
}
}
}

void traverse() // traversing the linked list


{ // no need for previous pointer in traversing
struct Node *ptr; // if you traverse from end then previous pointer will be
required
if (first == NULL)
{
cout << "list empty" << endl;
}
else
{
ptr = first;
while (ptr != NULL)
{
printf("data = %d\n", ptr->data);
ptr = ptr->next;
}
}
}
void search(int num) // this function is juct for telling
{ // wheather data is present or not
struct Node *ptr = NULL;
ptr = first;
while (ptr != NULL)
{
if (ptr->data == num)
{
cout << "found" << endl;
}
ptr = ptr->next;
}
}
int searchindex(int data) // this will tell the index of data
{
int index = 0;
struct Node *ptr = NULL;
ptr = first;
while (ptr != NULL)
{
if (ptr->data == data)
{
return index;
}
ptr = ptr->next;
index++;
}
return -1;
}

int main()
{
int check;
cout << "\n|\t1) insert\t|\n|\t2) traverse\t|\tmake sure to insert data before
traversing and searching\n|\t3) search\t|" << endl;
cin >> check;
if (check == 1)
{
int no_of_nodes;
cout << "enter number of nodes : ";
cin >> no_of_nodes;
insert(no_of_nodes);
cout << "\n2) traverse\n3) search" << endl;
cin >> check;
}
if (check == 2)
{
traverse();
cout << "\n3) search" << endl;
cin >> check;
}
if (check == 3)
{
cout << "enter data to be searched : ";
int sch;
cin >> sch;
search(sch);
cout << "element present at index " << searchindex(sch);
}
return 0;
}

You might also like