Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
2.2 kB
2
Indexable
Never
#include <stdio.h>
#include<stdlib.h>
struct node {
    int data;
    struct node *link;
};
node *head = NULL;
node *ptr = NULL;
void display() {
    node *temp = head;
    while (temp != NULL) {
        printf("%d\t", temp->data);
        temp = temp->link;
    }
}

void front()
{
    node *n4 = new node;
    if(n4 == NULL)
        printf("Memory Unavailable.");
    else
    {
    n4->link = head;
    printf("\nEnter value for the new node: \n");
    scanf("%d", &n4->data);
    head = n4;
    }
}

void end()
{
    node *n5 = new node;
    if(n5 == NULL)
        printf("Memory Unavailable.");
    else
    {
        ptr = head;
        while(ptr->link != NULL)
            ptr = ptr->link;
        ptr->link = n5;
        n5->link = NULL;
        printf("Enter the value for new node: ");
        scanf("%d", &n5->data);
    }
}

void middle()
{
    node *n6 = new node;
    if(n6 == NULL)
        printf("Memory Unavailable.");
    else
    {
        int key;
        ptr = head;
        printf("Enter the key: ");
        scanf("%d", &key);
        while(ptr->link != NULL)
        {
            if(ptr->data == key)
            {
                n6->link = ptr->link;
                ptr->link = n6;
                printf("Enter a value for the new node: ");
                scanf("%d", &n6->data);
                break;
            }
            else
                ptr = ptr->link;
        }
    }
}

int main() {
    node *n1 = new node;
    n1->data = 10;
    n1->link = NULL;

    node *n2 = new node;
    n2->data = 20;
    n2->link = NULL;

    node *n3 = new node;
    n3->data = 30;
    n3->link = NULL;

    head = n1;
    n1->link = n2;
    n2->link = n3;

    display();
    int ch;
    while(1)
    {
        printf("\n1.Insertion At Front. \n2.Insertion At Middle. \n3.Insertion At End \n4.Exit Operation. \n");
        scanf("%d", &ch);
        if(ch == 1)
        {
            front();
            display();
        }
        else if(ch == 2)
        {
            middle();
            display();
        }
        else if(ch == 3)
        {
            end();
            display();
        }
        else if(ch == 4)
            exit(0);
    }

}