Advertisement
Guest User

Untitled

a guest
Aug 21st, 2017
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.19 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include "list.h"
  5.  
  6.  
  7. Node * sort( Node * Head)
  8. {
  9. //Write your code here
  10. //bubble sort is simplest
  11. int sorted = 0;
  12. Node ** source = &Head;
  13. if (Head == NULL) {
  14. printf("Error, Head pointer points to NULL\n");
  15. }
  16. else
  17. {
  18. while(!sorted)
  19. {
  20. Node * current = Head;
  21. Node * next = current->next;
  22. Node * prev = NULL;
  23. sorted = 1;
  24. while (next != NULL)
  25. {
  26. if (current-> data > next->data)
  27. {
  28. sorted = 0;
  29. if (current == Head)
  30. {
  31. Head = next;
  32. }
  33. else
  34. {
  35. prev->next = next;
  36. }
  37.  
  38. current -> next = next->next; //swapping
  39. next->next = current;//swapping
  40. prev = next;//iterating
  41. next = current ->next; //iterating
  42. }
  43. else
  44. {
  45. prev = current;
  46. current = current->next;
  47. next = current -> next;
  48. }
  49.  
  50. }
  51. }
  52.  
  53. }
  54. return Head;
  55.  
  56.  
  57. }
  58.  
  59. int main(int argc, char* argv[])
  60. {
  61. FILE *ifp;
  62. char *mode = "r";
  63. Node *head;
  64. int num,i;
  65. char inputFilename[50];
  66. int *input;
  67. strcpy (inputFilename, argv[1]);
  68.  
  69. ifp = fopen(inputFilename, mode);
  70.  
  71. if (ifp == NULL)
  72. {
  73. fprintf(stderr, "Can't open the input file \n");
  74. exit(1);
  75. }
  76.  
  77.  
  78. while (fscanf(ifp, "%d", &num) == 1)
  79. {
  80. input = (int *) malloc(num*sizeof(int));
  81. for(i=0; i<num; i++)
  82. {
  83. fscanf(ifp, "%d",&input[i]);
  84. }
  85. head = createFullList(input, num);
  86. printf("Printing linked list...............\n");
  87. print(head);
  88. printf("Printing the sorted linked list...............\n");
  89. print( sort(head));
  90. free(input);
  91. }
  92.  
  93. fclose(ifp);
  94.  
  95. return 0;
  96. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement