Untitled

 avatar
unknown
plain_text
2 months ago
2.6 kB
4
Indexable
#include<stdio.h>
#include<stdlib.h>
struct node
{
    int data1;
    char data2;
    struct node* next;
};
struct node* head;
void createlist(int n);
void display();
void insert_beg();
void insert_end();
void insert_at_anyposition();
int main()
{
    int num;
    printf("Enter Total Number of Node\n");
    scanf("%d",&num);
    createlist(num);
    printf("Your Linked List is given below\n");
    display();
    insert_beg();
    display();
    insert_end();
    display();
    insert_at_anyposition();
    display();
    return 0;
}
void createlist(int n)
{
    struct node*fnode,*newnode;
    int i = 1;
    int val;
    char car;
    printf("Enter value for node %d:",i);
    scanf("%d %c",&val,&car);
    fnode = (struct node*)malloc(sizeof(struct node));
    fnode->data1 = val;
    fnode->data2 = car;
    fnode->next = NULL;
    head = fnode;
    for(int i = 2;i<=n;i++)
    {
        printf("Enter value for node %d:",i);
        scanf("%d %c",&val,&car);
        newnode = (struct node*)malloc(sizeof(struct node));
        newnode->data1 = val;
        newnode->data2 = car;
        fnode->next = newnode;
        newnode->next = NULL;
        fnode = newnode;
    }
}
void display()
{
    struct node* temp;
    temp = head;
    while(temp != NULL)
    {
        printf("%d %c\n",temp->data1,temp->data2);
        temp = temp->next;
    }
}
void insert_beg()
{
    struct node *newnode;
   newnode = (struct node*)malloc(sizeof(struct node));
   printf("Enter Data of the node to insert at beginning\n");
   scanf("%d %c",&newnode->data1,&newnode->data2);
   newnode->next = head;
   head = newnode;
}
void insert_end()
{
    struct node* tail = head;
    while(tail->next != NULL)
    {
        tail = tail->next;
    }
    
    struct node *newnode;
   newnode = (struct node*)malloc(sizeof(struct node));
   printf("Enter Data of the node to insert at End\n");
   scanf("%d %c",&newnode->data1,&newnode->data2);
   newnode->next = NULL;
   tail->next = newnode;
   tail = newnode;

}
void insert_at_anyposition()
{
    printf("Enter Position to insert new node\n");
    int pos;
    scanf("%d", &pos);
    printf("Enter Data of the node to insert at this position\n");
    struct node *newnode;
    newnode = (struct node *)malloc(sizeof(struct node));
    scanf("%d %c", &newnode->data1, &newnode->data2);
    struct node *temp = head;
    for (int i = 1; i <pos-1;i++)
    {
        temp = temp->next;
    }
    newnode->next = temp->next;
    temp->next = newnode;
}
Editor is loading...
Leave a Comment