Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Please Help Me Implement a template Linked-List class the code have \"empty, fir

ID: 3641462 • Letter: P

Question

Please Help Me Implement a template Linked-List class
the code have "empty, first, last, insert, and delete functions"
Here are the function prototypes
empty() ; //return true if the list is empty
first(); //return the pointer to the first node in the list
last(); //return the pointers to the last node in the list
insert(Node<T> * ptr, T value); //insert the given node after the given pointer and return a pointer the newly inserted node
erase(Node<T>* start, Node<T>* end = NULL); //remove all the nodes inclusively from start pointer to end pointer

thank you very much.

Explanation / Answer

#include <iostream.h>
#include <conio.h>

template <class T>
class Node
{
public:
T data;
Node* link;
};

template <class T>
class llist
{
Node<T> *f,*l;
public:
llist()
{ f=NULL;}
int empty()
{
return(f==NULL);
}
Node<T>* first()
{
return f;
}
Node<T>* last()
{
return l;
}
void addnode(T datain);
Node<T>* insert(Node<T> *ptr, T value);
void erase(Node<T>* start, Node<T>* end = NULL);

};
template<class T>

void llist<T>:: addnode(T datain)
{
Node<T> *pnew=new Node<T>;
pnew->data=datain;
pnew->link=NULL;

if(f==NULL)
f=l=pnew;
else
{
Node<T> *p;

p=f;
while(p->link)
p=p->link;

p->link=pnew;
l=pnew;
}
}
template<class T>

Node<T>* llist<T>::insert(Node<T> *ptr, T value)
{
Node<T> *p=f;

while(p!=NULL)
{
if(p==ptr)
{

Node<T> *pnew=new Node<T>;
pnew->data=value;
pnew->link=p->link;
p->link=pnew;
if(p==l)
l=pnew;
return pnew;
}
p=p->link;
}

return NULL;
}
template<class T>
void llist<T>::erase(Node<T>* start, Node<T>* end = NULL)
{
Node<T> *p1=f;
Node<T> *temp;
static int flag=1;
if(p1==start && (p1==end || p1->link==end))
{ if(flag==1)
{
cout<<"no elements between to delete"<<endl;
flag++;
}
else
return;
}
else
{
while(p1)
{
if(p1==start)
{
temp=p1->link;

}
if(p1==end)
{


erase(p1->link,end);
delete temp;
}
p1=p1->link;
}
if(p1==NULL)
cout<<"eithe start or end pointer is not present"<<endl;
}
}


int main()
{ clrscr();
llist<int> l;
l.addnode(10);
l.addnode(15);
l.addnode(12);

Node<int> *p=l.first();
Node<int> *t=l.last();
int x=30;
l.insert(p,x);


while(p)
{
cout<<p->data<<" ";
p=p->link;
}
l.erase(p,t);
cout<<"elements after deletions"<<endl;
while(p)
{
cout<<p->data<<" ";
p=p->link;
}
return 0;
}