Advertisement
Guest User

Untitled

a guest
Jan 20th, 2018
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.38 KB | None | 0 0
  1.  
  2. #include <stdio.h>
  3. //#include "stdafx.h"
  4. #include <malloc.h>
  5.  
  6.  
  7. struct node
  8. {
  9. int data;
  10. struct node *link;
  11. };
  12.  
  13. void addFirst(struct node **q, int data)
  14. {
  15. struct node *ptr = (struct node*)malloc(sizeof(struct node));
  16. ptr->data = data;
  17. ptr->link = *q;
  18. *q = ptr;
  19. }
  20.  
  21. void printList(struct node *head)
  22. {
  23. struct node *temp = head;
  24.  
  25. while (temp != NULL)
  26. {
  27. printf("%d", temp->data);
  28. printf("\n");
  29. temp = temp->link;
  30. }
  31.  
  32. }
  33.  
  34. void bubbleSort(struct node *head)
  35. {
  36. struct node *p, *q, *r, *s, *temp;
  37. s = NULL;
  38.  
  39. while(s != head->link)
  40. {
  41. {
  42. r = p = head;
  43. q = p->link;
  44. while (p != s)
  45. {
  46. if (p->data > q->data)
  47. {
  48. if (p == head)
  49. {
  50. temp = q->link;
  51. q->link = p;
  52. p->link = temp;
  53.  
  54. head = q;
  55. r = q;
  56. }
  57. else
  58. {
  59. temp = q->link;
  60. q->link = p;
  61. p->link = temp;
  62.  
  63. r->link = q;
  64. r = q;
  65. }
  66.  
  67. }
  68. else
  69. {
  70. r = p;
  71. p = p->link;
  72. }
  73. q = p->link;
  74. if (q == s)
  75. s = p;
  76. }
  77. } }
  78. }
  79.  
  80.  
  81. int main()
  82. {
  83. struct node *a = NULL;
  84. addFirst(&a, 5);
  85. addFirst(&a, 20);
  86. addFirst(&a, 4);
  87. addFirst(&a, 30);
  88. addFirst(&a, 20);
  89. addFirst(&a, 10);
  90. addFirst(&a, 9);
  91. addFirst(&a, 7);
  92.  
  93. printf("Initial list: \n");
  94. printList(a);
  95. bubbleSort(a);
  96. printf("Sorted list: \n");
  97. printList(a);
  98.  
  99. return 0;
  100. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement