Friday, 12 February 2016

Algorithm 5.4 (Insert Item in First Position in Linked List)


Before seeing the solution make sure that you tried enough. Don’t paste the whole code, just find out the logic. If you stuck in trouble, just inform me on comment.

/**Bismillahir Rahmanir Rahim.**/

#include <stdio.h>
#include <stdlib.h>
int m=1, i, x, n;
struct node
{
    int info;
    struct node* ptr;
};

struct node* start;
struct node* temp1;
struct node* temp2;

void insert(int x)
{
    temp1 = (struct node*) malloc(sizeof(struct node));
    temp1->info = x;
    temp1->ptr = NULL;
    if(m==1)
    {
        temp1->ptr = NULL;
        start = temp1;
        temp2 = temp1;
        m = 0;
        return ;
    }
    temp2->ptr = temp1;
    temp2 = temp1;
}

void insert_first()
{
    scanf("%d", &x);
    temp1 = (struct node*) malloc(sizeof(struct node));
    temp1->info = x;

    temp1->ptr = start;
    start = temp1;
}

void print()
{
    temp1 = start;
    printf("List is: ");
    while(temp1 != NULL)
    {
        printf(" %d ", temp1->info);
        temp1 = temp1->ptr;
    }
    printf("\n");
    free(temp1);
}
int main()
{
    start = NULL;
    printf("How Many Node??\n");
    scanf("%d", &n);
    printf("Print %d node :: \n", n);
    for(i=0; i<n; i++)
    {
        scanf("%d", &x);
        insert(x);
    }
    printf("Type what you want to Insert in First..........\n");
    insert_first();
    print();
    free(temp1);
    return 0;
}

First Input n = number of Total Node.  ex.   4.
second Input n node item . ex.     20  30  40  50.
Third Input what i want to insert. ex. 10.

Sample Input:
------------------

4
20 30 40 50
10

sample Output:
---------------------

List is : 10 20 30 40 50


0 comments:

Post a Comment

Note: only a member of this blog may post a comment.