Friday, January 24, 2020

Posted on Leave a Comment

Sorting elements of a singly linked list in ascending order

 A ‘C’ program to sort elements of a singly linked list in ascending order.

Sorting Elements Of A Singly Linked List


Sorting Singly list source code


#include
#include
#include

typedef struct NUM

{
  int data;
  struct NUM * link;
}
num;
num * createnode() {
  num * nn = NULL;
  nn = (num * ) malloc(sizeof(num));
  if (nn == NULL) {
    printf(“\n insufficient memory”);
    exit(0);
  } //end if
  return (nn);

} //end createnode

num * create() {
  num * hn = NULL, * cn = NULL, * nn = NULL;
  int i, n;
  printf(“\n enter no of node“);
  scanf(“ % d”, & n);
  printf(“\n enter data\ t”);
  for (i = 0; i < n; i++) {
    nn = createnode();
    scanf(“ % d”, & nn - > data);
    nn - > link = NULL;
    if (hn == NULL) {
      hn = nn;
      cn = nn;
    } //end if
    else {
      cn - > link = nn;
      cn = nn;
    }
  } //end for
  return (hn);
} //end create
void display(num * hn) {
  num * cn = NULL;
  num * temp, * j, * i;
  printf(“\n original data present in link list is“);
  for (cn = hn; cn != NULL; cn = cn - > link) {
    printf(” % d”, cn - > data);
  } //end for
  /*following code counts the nonzero,even,odd*/
  for (j = hn; j - > link != NULL; j = j - > link) {
    for (i = hn; i - > link != NULL; i = i - > link) {
      if (i - > data > i - > link - > data) {
        temp - > data = i - > data;
        i - > data = i - > link - > data;
        i - > link - > data = temp - > data;

      }
    }
  }
  printf(“\n data in ascending order is“);
  for (cn = hn; cn != NULL; cn = cn - > link) {
    printf(” % d”, cn - > data);
  }
} //end display
void main() {
  num * hn, * nn, * pn;
  int ch;
  clrscr();
  hn = create();
  display(hn);

  getch();
} //end main

Output


enter no of node 5
enter data 4 7 2 1 9
original data present in link list is 4 7 2 1 9
data in ascending order is 1 2 4 7 9

0 comments:

Post a Comment

Codearea.in is featured by projectsgeek.com. Powered by Blogger.