Tuesday, 9 February 2016

Algorithm 5.2 (Searching Item 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>

struct node
{
    int info;

    struct node* ptr;
};

struct node* start;
struct node* list;

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

    scanf("%d", &list->info);

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

void search(int item)
{
    list = start;
    int cndtn = 0, cnt = 0;
    while(list!=NULL)
    {
        cnt++;
        if(item == list->info)
        {
            printf("The location of this item is in %d\n", cnt);
            printf("The memory cell of this item is in %d\n\n", list);
            cndtn = 1;
        }

        list = list->ptr;
    }
    if(cndtn == 0) printf("Item is not in this list.\n");
    free(list);
}

int main()
{
    start = NULL;
    int  nde_num, i, item;
    scanf("%d", &nde_num);
    for(i=0; i<nde_num; i++)
        insert();
    scanf("%d", &item);
    search(item);
    free(list);
    return 0;
}

First Input nde_num = number of Total Node.  ex.  5.
second Input node item. ex.   10  20  30  40  50.
Third Input the item i want to search. ex. 40.

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

5
10 20 30 40 50
40

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

The location of this item is in 2
The memory cell of this item is in 5705048


0 comments:

Post a Comment

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