In: Computer Science
Write a program that create a single linked list and consist of all the necessary functions to do the following
Note:
You need to add proper documentation to your programs and you need to include the output of each program
C++
#include<iostream>
using namespace std;
//node structure
class node
{
public :
int d;
node *next;
node(int dd)
{
d=dd;
next=NULL;
}
};
//linked list
class single_linkedlist
{
public:
node *head,*tail;
single_linkedlist()
{
head=tail=NULL;
}
//method to add element to list
void add(int d)
{
if(head==NULL)
{
head = new
node(d);
tail=head;
}
else
{
tail->next=new node(d);
tail=tail->next;
}
}
//method to printlist
void print()
{
node *temp=head;
while(temp!=NULL)
{
cout<<temp->d<<"->";
temp=temp->next;
}
cout<<"\n";
}
//recursive method to delete a node at given position
void delete_atpos(node *h,int pos)
{
if(pos==0)
{
if(h==head)
{
head=head->next;
}
return;
}
else
{
int i=0;
node *cur,*prev=NULL;
cur = h;
while(i<pos)
{
prev=cur;
cur=cur->next;
i++;
}
if(cur!=NULL)
prev->next=cur->next;
else
prev->next=NULL;
}
}
};
int main()
{
single_linkedlist *d = new
single_linkedlist();///creating object
//creating linked list
d->add(1);
d->add(2);d->add(3);d->add(4);
//testing method 3a
cout<<"Current list :";
d->print();
single_linkedlist *dd = new
single_linkedlist();///creating object
//creating linked list
dd->add(8);
dd->add(2);dd->add(3);dd->add(1);
dd->add(7);
//testing method 3a
cout<<"Current list :";
dd->print();
dd->delete_atpos(dd->head,0);//deleting at
head
dd->print();
dd->delete_atpos(dd->head,3);//deleting at
tail
dd->print();
dd->delete_atpos(dd->head,1);//deleting in
middle
dd->print();
return 0;
}
output:
Current list :1->2->3->4->
Current list :8->2->3->1->7->
2->3->1->7->
2->3->1->
2->1->
Process exited normally.
Press any key to continue . . .