Program to implement Linked List using Struct in C/C++

Today i am going to show you how to implement linked list  type data array using structure. Linked ist is type of data structure in which dynamic memory allocation takes place, in short it is a type of flexible data array

Lets see:

#include "stdafx.h"
#include <iostream>
using namespace std;

struct Node
{
    int info;
    Node *next;

}*HEAD, *TPTR, *NEWN;

void case1(){
    int getinfo;
    cin >> getinfo;
    NEWN = new Node;
    NEWN->info = getinfo;
    NEWN->next = NULL;
    if (HEAD == NULL){
        HEAD = NEWN;
        cout << "Node added";
    }
    else
    {
        TPTR->next = NEWN;
    }

}
void case2(){
    int getinfo, found = 0;
    cout << "Elemnt to serach" << endl;
    cin >> getinfo;
    if (HEAD != NULL){

        TPTR = HEAD;
        while (TPTR->next != NULL)
        {
            if (TPTR->info == getinfo){
                cout << "Elemnt found" << endl;
                found = 1;
            }
            TPTR = TPTR->next;
        }
        if (TPTR->info == getinfo){
            cout << "Elemnt found" << endl;
        }
        else if (found == 0){
            cout << "not found" << endl;
        }
    }

    else {
        cout << "linked List empty" << endl;
    }
}
void case3(){
    if (HEAD != NULL){
        TPTR = HEAD;
        while (TPTR->next != NULL)
        {
            cout << " ELemnt is " << TPTR->info <<endl;
            TPTR = TPTR->next;
        }
        cout << " ELemnt is " << TPTR->info<<endl;
    }
    else
    {
        cout << "Empty" << endl;
    }
}


void main(){
    int opt = 0, getinfo, found = 0;
    while (opt != 4)
    {
        if (HEAD != NULL){
            TPTR = HEAD;

            while (TPTR->next != NULL)
            {
                TPTR = TPTR->next;//tptr points to last
            }
        }
        cout << "Choose an option " << endl << "1. Insert element" << endl << "2. Find Element" <<endl<<"3. List all"<< endl<<"4. Exit";
        cin >> getinfo;
        opt = getinfo;
        switch(opt){
        case 1:
            case1();
            break;
        case 2:
            case2();
            break;
        case 3:
            case3();
            break;
        case 4:
            opt = 4;
            break;
        default:
            cout << "error";
            break;
        }
        opt = 0;
    }

}

Share this:

ABOUT THE AUTHOR

Hello We are OddThemes, Our name came from the fact that we are UNIQUE. We specialize in designing premium looking fully customizable highly responsive blogger templates. We at OddThemes do carry a philosophy that: Nothing Is Impossible

0 comments:

Post a Comment