fork 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 != NULL) && (temp1->next != NULL)) {
  48. temp1 = temp1->next->next;
  49. temp2 = temp2->next;
  50. }
  51.  
  52. cout << temp2->value;
  53. }
  54.  
  55. int main()
  56. {
  57. insert_element2(1);
  58. insert_element2(2);
  59. insert_element2(3);
  60. insert_element2(4);
  61.  
  62. print_list(head);
  63. mid_list(head);
  64.  
  65. return 0;
  66. }
Success #stdin #stdout 0s 4376KB
stdin
Standard input is empty
stdout
1 2 3 4 
3