Friday, May 20, 2005

adding in ascending order in linked list

The code shows the adding in ascending order

 

 

 

 

#include "stdafx.h"

#include <conio.h>

 

struct node {

    struct node *link;

    int data;

};

void add(struct node **q, int num);

int display(struct node *p);

void free_list(struct node *p);

 

int _tmain(int argc, _TCHAR* argv[])

{

      struct node *p;

    int count;

 

    p = NULL;

 

      add(&p, 78);

    add(&p, 32);

    add(&p, 89);

    add(&p, 75);

    add(&p, 22);

    add(&p, 49);

    count = display(p);

    free_list(p);

    printf("The size of the linked list is: %d", count);

      getch();

      return 0;

}

 

void add(struct node **q, int num)

{

    struct node *r, *temp;

 

    temp = *q;

    r = (struct node*)malloc(sizeof *r);

    if (r == NULL) {

        exit(EXIT_FAILURE);

    }

    r -> data = num;

    if (*q == NULL || temp -> data >= num) {

        *q = r;

        (*q) -> link = temp;

    } else {

        for (;;) {

            if (temp -> link == NULL || temp -> link -> data >= num ) {

                r -> link = temp -> link;

                temp -> link = r;

                break;

            }

            temp = temp -> link;

        }

    }

 

 

}

 

 

int display(struct node *p)

{

    int count;

 

    for (count = 0; p != NULL; p = p -> link) {

        ++count;

        printf("%d\n", p -> data);

    }

    return count;

}

 

 

void free_list(struct node *p)

{

    struct node *next;

 

    while (p != NULL) {

        next = p -> link;

        free(p);

        p = next;

    }

}

 

 

 

Pradyut
http://pradyut.tk
http://groups.yahoo.com/group/d_dom/
http://groups-beta.google.com/group/oop_programming
India

 

No comments: