Friday 12 February 2016

Algorithm 5.3 (Searching Item in a Sorted 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, item;

struct node
{
    int INFO;
    struct node* PTR;
};

struct node* start;
struct node* LIST;
struct node* temp;

void insert(int x)
{
    LIST = (struct node*) malloc(sizeof(struct node));
    LIST->INFO = x;
    LIST->PTR = NULL;
    if(m==1)
    {
        LIST->PTR = NULL;
        start = LIST;
        temp = LIST;
        m = 0;
        return ;
    }
    temp->PTR = LIST;
    temp = LIST;

}
void search(int item)
{
    LIST = start;
    for(i=1; LIST != NULL; i++)
    {
        if(item > LIST->INFO)
            LIST = LIST->PTR;
        else if(item == LIST->INFO)
        {
            printf("Location :: %d\n", i);
            printf("Memory Cell :: %d\n", LIST);
            free(LIST);
            return;
        }
        else
        {
            printf("Item Is not In List.\n");
            free(LIST);
            return;
        }
    }
    free(LIST);
}
int main()
{
    start = NULL;
    scanf("%d", &n);
    for(i=0; i<n; i++)
    {
        scanf("%d", &x);
        insert(x);
    }
    scanf("%d", &item);
    search(item);
    free(LIST);
    return 0;
}

First Input n = number of Total Node.  ex.  5.
second Input n node item  (MUST BE SORTED) . 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:
---------------------

Location :: 4
Memory Cell :: 5705048


0 comments:

Post a Comment

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