Thursday, 28 January 2016

Insertion in Single Linked List

#include <iostream>
using namespace std;

struct node

{
    int data;
    node*link;
};

class linked_list
{
private: node *start, *cur, *temp;

public:

    linked_list()
  {
    start = NULL;
  }
        void append(int n)
        {
            if (start == NULL)
            {
                start = new node;
                start->data = n;
                start->link = NULL;
            }
            else
            {
                cur = start;
                while (cur->link != NULL)
                {
                    cur = cur->link;
                }
                temp = new node;
                temp->data = n;
                temp->link = NULL;
                cur->link = temp;
            }
        }
void print()
        {
            if (start == NULL)
                cout << "List empty";
            else
                cur = start;
            while (cur->link != NULL)
            {
                cout << cur->data;
                cur=cur->link;
            }
            cout << cur->data;
        }
};

int main()
{
    int n;
   linked_list obj;
    for (int i = 0; i < 5; i++)
    {
        cout << "Please Enter value for insertion: ";
        cin >> n;
        obj.append(n);
    }
    cout <<endl<< "Your Inserted values are: ";
    obj.print();
}

No comments:

Post a Comment

Tree Insertion

#include <iostream> using namespace std; struct node {     int data;     node*left;     node* right; }; class tree { priva...