fork(16) download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. typedef struct node{
  5. int data;
  6. struct node *ptr;
  7. } node;
  8.  
  9. node* insert(node* head, int num) {
  10. node *temp, *prev, *next;
  11. temp = (node*)malloc(sizeof(node));
  12. temp->data = num;
  13. temp->ptr = NULL;
  14. if(!head){
  15. head=temp;
  16. } else{
  17. prev = NULL;
  18. next = head;
  19. while(next && next->data<=num){
  20. prev = next;
  21. next = next->ptr;
  22. }
  23. if(!next){
  24. prev->ptr = temp;
  25. } else{
  26. if(prev) {
  27. temp->ptr = prev->ptr;
  28. prev-> ptr = temp;
  29. } else {
  30. temp->ptr = head;
  31. head = temp;
  32. }
  33. }
  34. }
  35. return head;
  36. }
  37.  
  38. void free_list(node *head) {
  39. node *prev = head;
  40. node *cur = head;
  41. while(cur) {
  42. prev = cur;
  43. cur = prev->ptr;
  44. free(prev);
  45. }
  46. }
  47.  
  48. int main(){
  49. int num;
  50. node *head, *p;
  51. head = NULL;
  52. do {
  53. printf("Enter a number");
  54. scanf("%d",&num);
  55. if(num) {
  56. head = insert(head, num);
  57. }
  58. } while(num);
  59. p = head;
  60. printf("\nThe numbers are:\n");
  61. while(p) {
  62. printf("%d ", p->data);
  63. p = p->ptr;
  64. }
  65. free_list(head);
  66. return 0;
  67. }
Success #stdin #stdout 0s 1968KB
stdin
2
1
4
9
-1
8
5
3
1
0
stdout
Enter a numberEnter a numberEnter a numberEnter a numberEnter a numberEnter a numberEnter a numberEnter a numberEnter a numberEnter a number
The numbers are:
-1 1 1 2 3 4 5 8 9