Please click on 1-2 Ads to keep this website's Study Material FREE and regularly Updated.

Program 39: Write a C++ program to make a singly linked list class.

#include<iostream>
using namespace std;

class node
{
	public:
		int data;
		node *next;
		node(int val=0,node *ptr=0)
		{
			data=val;
			next=ptr;
		}
};

class singly
{
	node *head=new node(0),*tail=new node(0);
	public:
		singly(node *h=0,node *t=0)
		{
			head=h;
			tail=t;
		}
		void add_at_value(int val)
		{
			node *n1=new node(val);
			if(head==0)
			{
				head=n1;
				tail=n1;
			}
			else
			{
				tail->next=n1;
				tail=n1;
			}
		}
		void display()
		{
			node *temp=head;
			while(temp!=0)
			{
				cout<<"\n"<<temp->data;
				temp=temp->next;
			}
		}
};

int main()
{
	int num,val;
	cout<<"\nenter the number of nodes : ";
	cin>>num;
	singly s;

	for(int i=0;i<num;i++)
	{
		cout<<"\ninput data for node "<<i+1<<" : ";
		cin>>val;
		s.add_at_value(val);
	}

	cout<<"\ndata entered in list : ";
	s.display();
	return 0;
}



If you have any suggestion or found any error in the above program, then do let us know at [email protected] or just comment below.