In: Computer Science
Linked List
Course Outcome:
CLO3 Build computer programs to implement appropriate data structures for solving computing problems in a time frame given. (P3, PLO3)
Task
Write a complete program by applying linked list data structure that will perform the following operation on any records:
Your program also should be able to display the number of record in the linked list. Put your creativity to produce the program.
Your Submission should have the following components:
Step1:
Everything About Code is Explained in Comments of Code:
#include <iostream>
using namespace std;
struct node
{
int data;
node *next;
node(int val)
{
data = val;
next = nullptr;
}
};
class LinkedList
{
private:
node *head;
node *end;
public:
//This functin will add the node
LinkedList()
{
head = end = nullptr;
}
void add(int val)
{
node *temp = new node(val);
if (end == nullptr)
{
end = temp;
head = end;
}
else
{
end->next = temp;
end = end->next;
}
}
//This function will delete the node having the data as key
void deleteNode(int key)
{
node *temp = head;
node *prev = head;
//checking if first node is same as key
if (temp != nullptr && temp->data == key)
{
head = temp->next;
free(temp);
return;
}
while (temp != nullptr && temp->data != key)
{
prev = temp;
temp = temp->next;
}
if (temp == nullptr)
return;
prev->next = temp->next;
free(temp);
}
//This Function will print the data of Linked List
void view_record()
{
cout << "Data : ";
node *temp = head;
while (temp != nullptr)
{
cout << temp->data << " ";
temp = temp->next;
}
cout << endl;
}
//This Function will return index of Node at which value gets find otherwise -1
int find(int val)
{
node *temp = head;
int res = 0;
while (temp != nullptr)
{
if (temp->data == val)
{
return res;
}
temp = temp->next;
res++;
}
return -1;
}
};
int main()
{
LinkedList list;
int n, val;
cout << "Enter the number of Elements:\n";
cin >> n;
cout << "Enter the Data:\n";
for (int i = 0; i < n; i++)
{
cin >> val;
list.add(val);
}
list.view_record();
cout << "Enter the value to be delete: \n";
cin >> val;
list.deleteNode(val);
list.view_record();
cout << "Enter the value to find: \n";
cin >> val;
int temp = list.find(val);
if (temp != -1)
cout << "Value is present in LinkedList at index: " << temp << endl;
else
{
cout << "Value Entered by User is not present:\n";
}
return 0;
}
Output:
Thanks