How to implement Linked List in C++
In this post, I am going to discuss the implementation of the linked list in C++ programming language.
There are many types of data structures one of the most important of those is Linked List.
Implementation of linked list in C++
A linked list is a form of a data structure(linear) in which we implement a list where each node(element) of the list is linked to the next node with the help of pointers.
A linked list consists of several nodes where each Node consists of two fields:
Feild 1: Data
Feild 2: Link to the next Node in the list
TYPES OF LINKED LIST:
CODE:
Below is the given C++ code for our task:
// Linked list insertion and Display in C++ #include<iostream> #include<malloc.h> using namespace std; struct Node { int data; struct Node *next; }; struct Node *head=NULL,*tail=NULL; void insertBeg() { struct Node *newNode; newNode=(struct Node*)malloc(sizeof(struct Node)); cout<<"Enter data :"; cin>>&newNode->data; newNode->next=head; if(head==NULL) head=tail=newNode; else { newNode->next=head; head=newNode; } } void insertEnd() { struct Node *newNode; newNode=(struct Node*)malloc(sizeof(struct Node)); cout<<"Enter data :"; cin>>&newNode->data; newNode->next=NULL; //imp here newNode->next=NULL if(head==NULL) head=tail=newNode; else { tail->next=newNode; tail=newNode; } } void insertPos(int p) { struct Node *temp,*temp1; int c=0; temp=temp1=head; while(temp!=NULL&&c<p) { temp1=temp; temp=temp->next; c++; } if(temp!=NULL) { struct Node *newNode; newNode=(struct Node*)malloc(sizeof(struct Node)); cout<<"Enter data :"; cin>>&newNode->data; newNode->next=temp; temp1->next=newNode; } } void display() { struct Node *temp; if(head==NULL) { cout<<"List is EMpty..."; return; } else { temp=head; while(temp!=NULL) { cout<<temp->data<<"\t"; temp=temp->next; } cout<<"\n"; } } int main() { insertBeg(); insertBeg(); cout<<"After Insertion At Begining :"; display(); insertEnd(); cout<<"After Insertion At end :"; display(); insertPos(2); cout<<"After Insertion At position 3 :"; display(); insertPos(3); cout<<"After Insertion At position 4 :"; display(); return 0; }
OUTPUT:
You may also learn:
Leave a Reply