• October 26, 2021

PHSARIT

Bring Technology Ideas with you

 Linked List in C++ Sample Code

Linked List is one of the linear data structure which can be used to make a collection of data with properly way. The linked List property must consists of a data and a pointer which refers to the address of each node in the collection. Below is the sample code in C++:

#include<iostream> 
#include<stdlib.h> 
#include<string> 
using namespace std;  
struct StudentList 
{ 
 string name; 
 struct StudentList *nextstudent; 
}; 
void insertData(struct StudentList** head, string newname)// insert at the beginning of the list 
{ 
 struct StudentList *newList = new StudentList; 
 newList->name = newname; 
 newList->nextstudent = (*head); 
 (*head) = newList; 
} 
void InsertAfterhead(struct StudentList** AfterHead, string nextname) 
{ 
 if (AfterHead == NULL) 
 { 
  cout << "Value of the pervious data cannot be nulled"; 
  return; 
 } 
 struct StudentList *newList = new StudentList; 
 newList->name = nextname; 
 newList->nextstudent = (*AfterHead); 
 (*AfterHead) = newList; 
} 
void insertEnd(struct StudentList** EndList, string endname) 
{ 
 struct StudentList *newList = new StudentList; 
 struct StudentList *last = *EndList; 
 newList->name = endname; 
 newList->nextstudent=NULL; 
 if (*EndList == NULL) 
 { 
  *EndList = newList; 
  return; 
 } 
 while (last->nextstudent!= NULL) 
 {  
  last = last->nextstudent; 
  last->nextstudent = newList; 
 return; 
 } 
} 
void ShowList(struct StudentList* n) 
{ 
 while (n != NULL) 
 { 
  cout << n->name << endl; 
  n = n->nextstudent; 
 } 
}  
int main() 
{ 
 struct StudentList* head = NULL; 
 insertData(&head, "Tola"); 
 //insertData(&head, "Pisey"); 
 insertData(&head, "Sehya"); 
 insertEnd(&head, "Sophal"); 
 InsertAfterhead(&head->nextstudent, "Visal"); 
 //insertEnd(&head, "Veasna"); 
 insertData(&head, "Pisey"); 
 ShowList(head); 
 system("pause==0"); 
} 

Related post