Monday, 30 March 2015

Linked List in C++

#include <iostream>
#include<conio.h>

using namespace std;

class Node {
private :
    int data;
    Node *next;
public :
    void setData( int data ){
        this->data = data;
   }
    void setNext(Node *node) {
        this->next = node;
    }
        Node* getNext(){
        return next;
    }
    int getData() { return data; }

};



class LinkedList
{
 private:
     Node *head;
     static int length ;

public :
   
    LinkedList(){ head = NULL; }
    void insertAtHead(int  );
    void deleteFromHead( );
    void displayList();
    int getLength(){ return length ; }
    bool isEmpty(){ return  (length == 0);  }

   
};
int LinkedList::length;

void LinkedList::insertAtHead(int data){
    Node *node = new Node();
    node->setData(data);

    Node *temp = head;
    head = node;
    node->setNext(temp);
    ++length;

}

void LinkedList::deleteFromHead(){
    if (isEmpty() )
    {
        cout << "List is empty  \n";
    }
    else
    {
        Node *temp = head;
        head = head->getNext();
        delete temp;
        --length;
    }

}

void LinkedList::displayList(){
    Node *temp = head;
   
    if ( isEmpty() ){
        cout << "Empty list";
    }
    else {
        while (temp != NULL)
        {

            int data = temp->getData();
            cout << data << " \n";
            temp = temp->getNext();
        }
    }

}


int main()
{
    LinkedList list;

    list.insertAtHead(1);
    list.insertAtHead(2);
    list.insertAtHead(3);
    list.insertAtHead(4);
    list.insertAtHead(5);

    list.displayList();

    list.deleteFromHead();
    list.deleteFromHead();
    list.deleteFromHead();
    list.deleteFromHead();
    list.deleteFromHead();

    list.displayList();

    getchar();
    return 0;

   



}

No comments:

Post a Comment