The code below is my implementation of singly linked list.I would prefer it, if you kindly review the code and give me pointers on how a professional programmer would have written the code. Basically, i want to know about some good code habits that I have missed in the code.
The class one_way_linked_list is the linked list class. It uses the node class to create the nodes of the list. It keeps record of every object's head node using the head pointer. The function list_create() creates the list. The function list_print() prints the code. The function list_delete() deletes the linked list by deallocating every node one by one.
Sorry for my english, as it is not my native language. Thank you in advance.
#include <iostream>
using namespace std;
template<typename t>
class node
{
public:
t data;
node *next;
//constructors
node()
{
next=NULL;
}
node(t d)
{
data=d;
next=NULL;
}
};
template<typename t>
class one_way_linked_list
{
node<t> n;
public:
node<t> *head=NULL;
node<t> *prev=NULL;
void list_create(t);
void list_print();
void list_delete()
};
template <typename t>
void one_way_linked_list<t>::list_create(t dat)
{
node<t> *ptr=new node<t>(dat);
if(head==NULL)
{
head=ptr;
prev=head;
}
else
{
prev->next=ptr;
prev=ptr;
}
}
template<typename t>
void one_way_linked_list<t>::list_print()
{
node<t> *ptr=this->head;
cout<<"Printing the list: "<<endl;
while(ptr!=NULL)
{
cout<<ptr->data<<" ";
ptr=ptr->next;
}
cout<<endl;
}
template<typename t>
void one_way_linked_list<t>::list_delete()
{
node<t> *ptr=new node<t>();
ptr->data=this->head->data;
while(ptr!=NULL)
{
ptr=ptr->next;
delete ptr;
}
delete this->head;
head=NULL;
cout<<"Deleted"<<endl;
}
int main()
{
//driver program for int type list
one_way_linked_list<int> list1;
int temp;
while(1)
{
cin>>temp;
if(temp==-1) break;
else
{
list1.list_create(temp);
}
}
list1.list_print();
list1.list_delete();
list1.list_print();
}
std::forward_list
? Or - are you doing this just as an exercise in coding? \$\endgroup\$