fork download
  1. #include <iostream>
  2.  
  3. using std::cout;
  4. using std::endl;
  5.  
  6. class LinkedList
  7. {
  8. struct Node
  9. {
  10. int x;
  11. Node *next;
  12. };
  13.  
  14. Node *head;
  15.  
  16. // get a pointer to the last node in the list.
  17. // returns: head if the list is empty.
  18. Node* last_node()
  19. {
  20. Node* cur = head;
  21. while (cur->next)
  22. cur = cur->next;
  23. return cur;
  24. }
  25.  
  26. public:
  27. LinkedList()
  28. : head(new Node { -1, nullptr })
  29. {
  30. }
  31.  
  32. // If you absolutely have to have a constructor that adds a node:
  33. LinkedList(int adds) : LinkedList()
  34. {
  35. add(adds);
  36. }
  37.  
  38. ~LinkedList() // destructor
  39. {
  40. // Free all of the nodes we created
  41. Node *next;
  42. for (Node* cur = head; cur != nullptr; cur = next) {
  43. next = cur->next;
  44. delete cur;
  45. }
  46. }
  47.  
  48. void add(int adds)
  49. {
  50. Node* tail = last_node();
  51. tail->next = new Node { adds, nullptr };
  52. cout << "added: " << tail->next->x << endl;
  53. }
  54.  
  55. bool empty() const
  56. {
  57. return (head->next == nullptr);
  58. }
  59.  
  60. // returns: value of the last node (-1 if list is empty)
  61. int back()
  62. {
  63. return last_node()->x;
  64. }
  65.  
  66.  
  67. // Normal implementation requires caller to check !empty() first:
  68.  
  69. // returns: value of the first non-head node
  70. // if the list is empty, undefined behavior.
  71. int front()
  72. {
  73. return head->next->x;
  74. }
  75.  
  76. // alternatively:
  77.  
  78. // returns: value of the first non-head node or -1 if the list is empty.
  79. int front_safe()
  80. {
  81. return (head->next) ? head->next->x : head->x;
  82. }
  83. };
  84.  
  85. int main()
  86. {
  87. LinkedList lt;
  88. lt.add(1);
  89. lt.add(2);
  90. lt.add(3);
  91. lt.add(4);
  92. cout << lt.front() << endl;
  93. cout << lt.back() << endl;
  94. }
  95.  
Success #stdin #stdout 0s 3456KB
stdin
Standard input is empty
stdout
added:  1
added:  2
added:  3
added:  4
1
4