Saturday 13 February 2016

Algorithm 5.8 (Deleting Item from nth 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.

/**Bismillair Rahmanir Rahim.**/

#include <stdio.h>
#include <stdlib.h>
int m=1, i, x, n, nth;
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 delte()
{
    printf("Which Node You Want To delete ::\n");
    scanf("%d", &nth);
    list = start;
    if(nth == 1)
    {
        list = list->ptr;
        start = list;
        return;
    }
    for(i=0; i<nth-1; i++)
    {
        temp = list;
        list = list->ptr;
    }
    temp->ptr = list->ptr;
}
void print()
{
    list = start;
    printf("List is: ");
    while(list != NULL)
    {
        printf(" %d ", list->info);
        list = list->ptr;
    }
    printf("\n");
    free(list);
}
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);
    }
    delte();
    print();
    free(list);
    return 0;
}

First Input n = number of Total Node.  ex.   5.
second Input n node item . ex.     10  20  30  40  50.
In which node i want to Delete. ex. 2.

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

5
10 20 30 40 50
2

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

List is : 10 30 40 50


0 comments:

Post a Comment

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