Advertisement
Guest User

Untitled

a guest
Feb 20th, 2020
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.98 KB | None | 0 0
  1. #include <iostream>
  2. using std::cin;
  3. using std::cout;
  4. using std::endl;
  5.  
  6. class Node
  7. {
  8. public:
  9. int data;
  10. Node *next;
  11. };
  12.  
  13. void insert(Node **head, Node *new_node)
  14. {
  15. Node *curr;
  16. if (*head == NULL || (*head)->data >= new_node->data)
  17. {
  18. new_node->next = *head;
  19. *head = new_node;
  20. }
  21. else
  22. {
  23. curr = *head;
  24. while (curr->next != NULL && curr->next->data < new_node->data)
  25. {
  26. curr = curr->next;
  27. }
  28. new_node->next = curr->next;
  29. curr->next = new_node;
  30. }
  31. }
  32.  
  33. void sort(Node **head)
  34. {
  35. Node *sorted = NULL;
  36. Node *curr = *head;
  37.  
  38. while (curr != NULL)
  39. {
  40. Node *next = curr->next;
  41. insert(&sorted, curr);
  42. curr = next;
  43. }
  44. *head = sorted;
  45. }
  46.  
  47. //taken fron assignment 2/3
  48. void enqueue(Node **head, int data)
  49. {
  50. Node *new_node = new Node();
  51.  
  52. new_node->data = data;
  53. new_node->next = *head;
  54. *head = new_node;
  55. }
  56.  
  57. //also taken from assignment 2/3
  58. int get(Node *head, int num)
  59. {
  60. Node *cur = head;
  61. int count = 0;
  62.  
  63. while (cur != NULL)
  64. {
  65. if (count == num)
  66. {
  67. return cur->data;
  68. }
  69. count++;
  70. cur = cur->next;
  71. }
  72. }
  73.  
  74. //also also taken from assignment 2/3
  75. void print_list(Node *node)
  76. {
  77. while (node != NULL)
  78. {
  79. cout << node->data << ",";
  80. node = node->next;
  81. }
  82. }
  83.  
  84. int main()
  85. {
  86. Node *head = NULL;
  87.  
  88. cout << endl
  89. << "Linked list: ";
  90. enqueue(&head, 47);
  91. enqueue(&head, 53);
  92. enqueue(&head, 77);
  93. enqueue(&head, 29);
  94. enqueue(&head, 81);
  95. enqueue(&head, 20);
  96. enqueue(&head, 99);
  97. enqueue(&head, 0);
  98. print_list(head);
  99. cout << endl;
  100.  
  101. sort(&head);
  102. cout << endl
  103. << "Sorted linked list: ";
  104. print_list(head);
  105.  
  106. cout << endl
  107. << endl
  108. << "Get element check (position 4): " << get(head, 4) << endl
  109. << endl;
  110. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement