Wednesday, May 25, 2016

NIELIT M3-R4: Q.No. 7(b) January 2013

M3-R4: January 2013 (O-Level)

Q. 7(b):
Write a program to create a link list. There should be 10 nodes in the list, each node contains an integer between 1 – 10. The list should be printed at the end.

Ans:
We are putting random numbers between 1 and 10 here: 

#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <alloc.h>

struct node{
    int inf;
    struct node *next;
};

struct node * add(struct node *list, int info){
    struct node *temp;
    temp = malloc(sizeof(struct node *));
    temp->inf = info;
    temp->next = NULL;
    if(list == NULL){
        list = temp;
    }
    else{
        temp->next = list;
        list = temp;
    }
    return list;
}

void display(struct node *list){
    printf("\n");
    while(list != NULL){
        printf("%d -> ",list->inf);
        list = list->next;
    }
    printf("NULL");
}

void main(){
    struct node *linkedlist = NULL;
    int i=0,info;
    randomize();
    for(i=0;i<10;i++){
        info = rand()%10 + 1;
        linkedlist = add(linkedlist,info);
    }
    display(linkedlist);
    getch();
}

No comments:

Post a Comment