Implementation of Linked List in C++ with examples
Contents
Linked list in C++
Linked list is one of the data structure that used to overcome the limitation of array. The implementation of a linked list in C++ is done using pointers. Each element in the linked list is called as node. The node contains two different fields. The first field holds the data and the second field holds the address of the next node.
Types of Linked list:
There are 3 types of linked list used in the programs
1)Singly Linked List
2)Doubly Linked List
3)Circular Linked List
Singly Linked List:
In this linked list, Each node contains the data and address of the next node. Only the reference to the first list node is required to access the whole linked list. This is known as the head. The last node in the list points to nothing so it stores NULL in that part.
Doubly Linked List:
In this linked list, Each node contains the data ,address of the both previous node and next node.We can either go forward or backward direction based on the address of the node.
Circular Linked List:
A circular linked list is a variation of linked list in which the last element is linked to the first element. This forms a circular loop.
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 |
#include <iostream> using namespace std; //Declare Node struct Node{ int num; Node *next; }; //Declare starting (Head) node struct Node *head=NULL; //Insert node at start void insertNode(int n){ struct Node *newNode=new Node; newNode->num=n; newNode->next=head; head=newNode; } //Traverse/ display all nodes (print items) void display(){ if(head==NULL){ cout<<"List is empty!"<<endl; return; } struct Node *temp=head; while(temp!=NULL){ cout<<temp->num<<" "; temp=temp->next; } cout<<endl; } //delete node from start void deleteItem(){ if(head==NULL){ cout<<"List is empty!"<<endl; return; } cout<<head->num<<" is removed."<<endl; head=head->next; } int main(){ cout<<"<---- Singly Linked List ----->" <<endl; display(); insertNode(121); cout<<"<-- Linked List after inserting a first node --->" <<endl; display(); insertNode(122); cout<<"<-- Linked List after inserting a second node --->" <<endl; display(); insertNode(123); cout<<"<-- Linked List after inserting a third node --->" <<endl; display(); cout<<"<-- Deleting the node one by one from third node to first --->" <<endl; deleteItem(); deleteItem(); deleteItem(); display(); return 0; } |
Output:
Recommended Articles