Friday 5 February 2016

Algorithm 5.1 (Traversing a 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>

struct node
{
    char name[50];
    int age;
    int roll;
    char sex[10];
    char phone[20];
    struct node* ptr;
};

struct node* start;
struct node* list;

void insert()
{
    struct node* list = (struct node*) malloc(sizeof(struct node));

    getchar();

    gets(list->name);
    scanf("%d", &list->age);
    scanf("%d", &list->roll);
    scanf("%s", list->sex);
    scanf("%s", list->phone);

    list->ptr = start;
    start = list;
}

void traverse()
{
    list = start;
    while(list!=NULL)
    {
        list->age += 5;

        list = list->ptr;
    }
}

void print()
{
    list = start;
    while(list!=NULL)
    {
        printf("Name  : %s\n", list->name);
        printf("Age   : %d\n", list->age);
        printf("Roll  : %d\n", list->roll);
        printf("Sex   : %s\n", list->sex);
        printf("Phone : %s\n\n", list->phone);

        list = list->ptr;
    }
    free(list);
}

int main()
{
    start = NULL;
    int  nde_num, i;
    scanf("%d", &nde_num);
    for(i=0; i<nde_num; i++)
        insert();
    traverse();
    printf("\n----------------------------\n");
    print();
    free(list);
    return 0;
}

First Input nde_num = number of Total Node.
next every node contain 5 input.
They Are name, age, roll, sex and phone number gradually.

sample input:
------------------
 
4
Aminul Islam Mamun.
21
11508003
Male
01762621438
Mahmudul Amin Minar.
20
11508017
Male
01521435336
Abu Bakar Siddique.
20
11508002
Male
01746781211
Saifur Rahman.
20
11508030
Male
01758758468


on output we traverse the list and add 5 years age on every person.

sample Output
-------------
----------------------------
Name  : Saifur Rahman.
Age     : 25
Roll    : 11508030
Sex     : Male
Phone : 01758758468

Name  : Abu Bakar Siddique.
Age     : 25
Roll    : 11508002
Sex     : Male
Phone : 01746781211

Name  : Mahmudul Amin Minar.
Age     : 25
Roll    : 11508017
Sex     : Male
Phone : 01521435336

Name  : Aminul Islam Mamun.
Age     : 26
Roll    : 11508003
Sex     : Male
Phone : 01762621438


1 comment:

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