Beruflich Dokumente
Kultur Dokumente
10914802719
Experiment No.5
Operations on a linked list
PROGRAM:
#include<iostream>
using namespace std;
struct Node //Declaring the structure of the Node
{
int data;
Node* next;
};
void insert (Node*& head,int key,int pos)
{
//Function to perform insertion on a linked list
Node* t = new Node;
t->data = key;
t->next = NULL;
if (head == NULL)//This means that the list is
empty
Saksham Sharma
10914802719
{
head = t;
return;
}
Node* p = head;
if (pos == 1)
//if position is 1 this means that we have to
insert at the beginning of the list
{
t->next = head;
head = t;
return;
}
pos -= 2;
while (pos--)
{
p = p->next;
}
t->next = p->next;
p->next = t;
}
void Display(Node* head)
//This function is for traversing and displaying
all the elements in the linked list
Saksham Sharma
10914802719
{
cout<<"Linked list is: ";
while (head)
{
cout << head->data << " ";
head = head->next;
}
}
void Delete(Node*& head,int pos)
//This function deletes the node at a particular
position
{
Node* p = head;
//We will point this pointer p on the node to
be deleted
Node* tail = head;
//Tail should point to the node just before the
node that is to be deleted
pos--;
while (pos--)
{
tail = p;
p = p->next;
}
Saksham Sharma
10914802719
if (p == head)
{
head = head->next;
delete p;
return;
}
tail->next = p->next;
p->next = NULL;
delete p;
//this will deallocate the memory of the node on
which p is pointing at
}
int main()
{
int key, pos,oper;
cout<< "1.Insert\n2.Traverse/Display\n3.Delete\n";
cout << "Enter the number of operations ";
cin >> oper;
int choice;
Node* head = NULL;
while (oper--)
{ cout << "Enter the choice ";
cin >> choice;
if (choice == 1)
Saksham Sharma
10914802719
{
cout << "Enter the position and the key
";
cin >> pos >> key;
insert(head, key, pos);
cout << endl;
continue;
}
if (choice == 2)
{
Display(head);
cout << endl;
}
else
{
cout << "Enter the position of the element
to delete ";
cin >> pos;
Delete(head,pos);
cout << endl;
}
}
return 0;
}
Saksham Sharma
10914802719
OUTPUT
Saksham Sharma
10914802719
VIVA QUESTIONS