Write a C++ program to demonstrate Generic Linked List
Here we are going to make a generic LinkedList so a generic LinkedList is a, Linked list using a void pointer is a generic linked list. That is, it can store any kind of data that the user wishes to enter. A void pointer can store the address of any data type, this means that the program can store any data type that the user requires.
C++ program of generic linked list
#include <iostream> using namespace std; // declaring node class template<class L> struct node { node<L>* next; L data; }; // declaring linked list class template<class L> class LinkedList { public: node<L>* head; node<L>* last; LinkedList<L>() { head = NULL; last = NULL; } void add(L data) { if(!head) { // when there is no element in the list head = new node<L>; head->data = data; head->next = NULL; last = head; } else { // when the list is not empty if(last == head) { // when the list has one element last = new node<L>; last->data = data; last->next = NULL; head->next = last; } else { // when the list has more than one element node<L>* insdata = new node<L>; insdata->data = data; insdata->next = NULL; last->next = insdata; last = insdata; } } } L get(int index) { if(index == 0) { // returning the head element return this->head->data; } else { // Get the index'th element node<L>* curr = this->head; for(int i = 0; i < index; ++i) { curr = curr->next; } return curr->data; } } L operator[](int index) { return get(index); } }; int main(int argc, char const *argv[]) { LinkedList<string> Str; Str.add("Hello"); cout<<Str.get(0)<<endl; LinkedList<int> INT; INT.add(4); cout<<INT.get(0); }
Function implementation
- add() -:
this function inserts data in LinkedList - get() -:
this function returns the data in the LinkedList.
Implementation
A template node class is created which contains data and the next pointer then, the LinkedList class is created in which there are two users define data, head, and last. Both of them are NULL at this point as the LinkedList is empty. Then a member function is created “add” this check if the list is empty or not and according to the situation it adds data into LinkedList. Then another function created that is “get” this function returns the data from the LinkedList. In the main function, an object of the list is created. Then objects can store any kind of data for example string, int, char, etc. Afterward add is called and data is inserted in the list and finally get is called to get the data from the list.
Output
Below is the output of our program:
Hello 4
Leave a Reply