Linked List Program in C++

Linked list is a type of data structure that contains many nodes. Generally nodes has two parts such as data and the reference to the next node. The first node in any linked list called head.

The head has all the data’s and referential nodes list. The last node in the linked list contains NULL character. The referential nodes is nothing but pointers to find the next node.

Linked List Program in C++

The elements are linked together using pointers. This is the most usable data structure after arrays. The list elements are stored in location in arrays. But pointers are used to link elements in linked list.

Unlike arrays insert an element or delete an element is is very easy in linked list. But insert an element in array is very expensive.

Linked List Program in C++

#include <iostream>
using namespace std;
struct Node {
   int data;
   struct Node *next;
};
struct Node* head = NULL;
void insert(int new_data) {
   struct Node* new_node = (struct Node*) malloc(sizeof(struct Node));
   new_node->data = new_data;
   new_node->next = head;
   head = new_node;
}
void display() {
   struct Node* ptr;
   ptr = head;
   while (ptr != NULL) {
      cout<< ptr->data <<" ";
      ptr = ptr->next;
   }
}
int main() {
   insert(3);
   insert(1);
   insert(7);
   insert(2);
   insert(9);
   cout<<"The linked list is: ";
   display();
   return 0;
}
Read Also : Selection Sort in C++

Output

The linked list is: 9 2 7 1 3

Final Words

I hope this article helps you to find Linked List in C++ Program. If you face any issues please let me know via the comment section. Share this article with other C++ program developers via social networks.

Share on:

Hi, I'm Ranjith a full-time Blogger, YouTuber, Affiliate Marketer, & founder of Coding Diksha. Here, I post about programming to help developers.

Leave a Comment