fork(1) download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. struct Node {
  5. int value;
  6. Node* next;
  7. };
  8.  
  9. Node* head = NULL;
  10.  
  11. void insert_element2(int x)
  12. {
  13. Node* temp1 = new Node();
  14. temp1->value = x;
  15. temp1->next = NULL;
  16.  
  17. if (head == NULL)
  18. head = temp1;
  19. else {
  20. Node* temp2 = head;
  21. while(temp2->next != NULL) {
  22. temp2 = temp2->next;
  23. }
  24. temp2->next = temp1;
  25. }
  26. }
  27.  
  28. void print_list(Node* head)
  29. {
  30. Node* temp = head;
  31.  
  32. while (temp != NULL) {
  33. cout << temp->value << ' ';
  34. temp = temp->next;
  35. }
  36.  
  37. cout << endl;
  38. }
  39.  
  40. void mid_list(Node* head)
  41. {
  42. if (head == NULL) return;
  43.  
  44. Node* temp1 = head;
  45. Node* temp2 = head;
  46.  
  47. while (temp1->next != NULL) {
  48. temp1 = temp1->next->next;
  49. if (temp1 == NULL) break;
  50. temp2 = temp2->next;
  51. }
  52.  
  53. cout << temp2->value;
  54. }
  55.  
  56. int main()
  57. {
  58. insert_element2(1);
  59. insert_element2(2);
  60. insert_element2(3);
  61. insert_element2(4);
  62.  
  63. print_list(head);
  64. mid_list(head);
  65.  
  66. return 0;
  67. }
Success #stdin #stdout 0s 4188KB
stdin
Standard input is empty
stdout
1 2 3 4 
2