linked list in c++ using class:
This is singly linked list implementation, it travel in one direction that is forward direction so it is also called as “Forward list”.
insertion and deletion in linked list in c++ program:
Below program explain insertion, deletion, display and other functionalities.
source code of linked list in c++
/* Program: Singly Linklist Author: Alpha Master Date: 20 Oct 2021 */ //Header File #include<iostream> struct node { int data; node* next; }; class linklist { node* ptr; public: linklist(); ~linklist(); void append(int num); void display(); void addAtBeg(int num); bool find(int num); void remove(int num); }; linklist::linklist() { ptr = nullptr; } linklist::~linklist() { node* tmp = nullptr; while(ptr != nullptr) { tmp = ptr->next; delete ptr; ptr = tmp; } } void linklist:: display() { node* tmp = ptr; while(tmp != nullptr) { std::cout<<tmp->data<<" "; tmp = tmp->next; } std::cout<<std::endl; } void linklist::append(int num) { //first element if(ptr == nullptr) { ptr = new node; ptr->data = num; ptr->next = nullptr; } else { //traverse till end node* tmp = ptr; node* pre = nullptr; while(tmp != nullptr) { pre = tmp; tmp = tmp->next; } pre->next = new node; pre->next->data = num; pre->next->next = nullptr; } } void linklist::addAtBeg(int num) { node* tmp = nullptr; tmp = ptr; ptr = new node; ptr->data = num; ptr->next = tmp; } bool linklist::find(int num) { node* tmp = ptr; bool result = false; while(tmp != nullptr) { if(tmp->data == num) { result = true; break; } tmp = tmp->next; } return result; } void linklist::remove(int num) { node* tmp = ptr; node* pre = tmp; while(tmp != nullptr) { if(tmp->data == num) { if(tmp == ptr) ptr = ptr->next; else pre->next = tmp->next; //delete delete tmp; break; } pre = tmp; tmp = tmp->next; } } int main() { std::cout<<"Single LinkList"<<std::endl; linklist obj; obj.append(1); obj.append(2); obj.append(3); obj.addAtBeg(4); obj.append(5); obj.display(); std::cout<<obj.find(3)<<std::endl; std::cout<<obj.find(5)<<std::endl; std::cout<<"Remove 4"<<std::endl; obj.remove(4); obj.display(); std::cout<<"Remove 2"<<std::endl; obj.remove(2); obj.display(); std::cout<<"Remove 5"<<std::endl; obj.remove(5); obj.display(); return 0; }
Output:
Single LinkList 4 1 2 3 5 1 1 Remove 4 1 2 3 5 Remove 2 1 3 5 Remove 5 1 3