Simple GUI Notepad Using Ruby

GUI Notepad Using Ruby Code require 'tk' class Notepad def saveFile file = File.open("note", "w") ...

Sunday, March 1, 2015

Linked List Implementation In C++ Using Friend Class

Linked List is one of the most common data structures available. In C++ we already have List in STL but in this program we will implement out own link list class using friend class.



#include <iostream>
using namespace std;

class Node
{
    friend class List;
    int val;
    Node *link; 
    public:
        Node() {
            val = 0;
            link = NULL;
        }
        Node(int v) {
            val = v;
            link = NULL;
        }
        Node(int v, Node *p) {
            val = v;
            link = p;
        }
};

class List
{
    int size;
    Node *head;
    public:
        List() {
            head = new Node();
            size = 0;
        }
        void append(int);
        void show() const;
        inline int len() {
            return size;
        }
};

void List::append(int item)
{
    Node *pivot = new Node(item);
    if (size == 0) {
        head->link = pivot;
    }
    else {
        Node *temp = head;
        while (temp->link != NULL) {
            temp = temp->link; 
        }
        temp->link = pivot;
    }
    size++;
}

void List::show() const
{
    Node *tmp = head->link;
    cout << "[";
    while (tmp != NULL) {
        cout << tmp->val << "," << ends;
        tmp = tmp->link;
    }
    cout << "\b\b]" << endl;
}

int main()
{
    List a;
    
    a.append(1);
    a.append(2);
    a.append(3);
    a.append(4);
    a.show();
    
    a.append(5);
    a.append(6);
    a.append(7);
    a.show();
    
    cout << "Length Of The List: "<< a.len() << endl;
    
    return 0;   
}
[1, 2, 3, 4]
[1, 2, 3, 4, 5, 6, 7]
Length Of The List: 7

--------------------------------
Process exited after 0.3124 seconds with return value 0
Press any key to continue . . .