This is just a beginners code for the simple singly linear linked list .Once we get strong in the linear linked list, its very easy to proceed further in the complex data structures part. To understand this code you just need to know the basics of linked list,pointers,C++.

Here is the source code


/* The simple singly linear linked list program written in C/C++
This creates a head node of linked list first and insert the new nodes to the end of linked list .
You have to define the maximum size of linked list on start run .
*/
#include<iostream.h>

struct list
{
int value;
struct list * next;
};

struct list * insert( struct list *, int);

int main()
{
struct list *head=(struct list *) malloc(sizeof(struct list));
cout <<"Enter the total no of nodes to be present in the linked list\n";
int total_element;
cin >> total_element;
cout<< "Enter the head value\n";
/* Create a head node and assign the value also assign the next node address to NULL (The linked list will end with a node whose next address is NULL */
cin >> head ->value;
head->next=NULL;
for(int i=1;i<total_element;i++) {
cout<<"Enter the next node value \n";
int new1;
cin>>new1;
// The insert function gets the head pointer and new value as arguments
head= insert(head,new1);
}
// Start from the head and display all the nodes in the linked list till the node is NULL
struct list *disp=head;
cout <<" The display of the inserted linked list is \n";
while(disp!=NULL)
{
cout<<"-->"<value;
disp=disp->next;
};
}
// Here we need to goto the end of the current linked list and create a new element and link there, finally return the head pointer
struct list * insert( struct list *head, int newvalue)
{
struct list *new1=(struct list *) malloc(sizeof(struct list));
struct list *temp = head;
while(temp->next!=NULL)
{
temp=temp->next;
}
new1 ->value=newvalue;
new1->next=NULL;
temp->next=new1;
return head;
};

Related Posts :



Bookmark and Share