LinkedList C++ using OOP



#include <iostream>

using namespace std;


//NODE

class Node{

public:

int data;

Node* next;

//CONSTRUCTORS

Node(){

data=0;

next=NULL;

}

Node(int d){

data =d;

next= NULL;

}

Node(int d,Node* n){

data=d;

next=n;

}

};

//LINKED LIST

class LinkedList{

private:

Node* head;

Node* tail;

public:


//CONSTRUCTORS

LinkedList(){

Node();

head=tail=NULL;

}

//METHODS

void displayLinkedList();

void InsertAtHead(int d);

void InsertAtTail(int d);

};

//DISPLAY

void LinkedList::displayLinkedList(){

if(head==NULL)

cout<<"Linked List is empty"<<endl;

Node* temp =head;

while(temp != NULL){

cout<<temp->data<<"\t";

temp=temp->next;

}

}

//INSERT AT HEAD

void LinkedList::InsertAtHead(int d){

Node* temp = new Node(d,NULL);

if(head == NULL)

tail= temp;

else{

temp->next = head;

}

head=temp;

}

//INSERT AT TAIL

void LinkedList::InsertAtTail(int d){

Node* temp = new Node(d,NULL);

if(head == NULL){

head=temp;

tail=temp;

}

else{

tail->next=temp;

tail=temp;

}

}

//MAIN

int main(){

LinkedList obj1; //an object "obj1" of class "LinkedList" is created 

obj1.InsertAtHead(6);

obj1.InsertAtHead(5);

obj1.InsertAtTail(7);

obj1.InsertAtHead(0);

obj1.displayLinkedList();

return 0;

}

Comments