fork(1) download
  1. #include <iostream>
  2.  
  3. // For simplicity, keeping everything public
  4. template<class T>
  5. class Node
  6. {
  7. public:
  8. Node(T data) : data(data), prev(nullptr), next(nullptr) {}
  9.  
  10. T data;
  11. Node* prev;
  12. Node* next;
  13. };
  14.  
  15. template<class T>
  16. class MyLinkedList
  17. {
  18. public:
  19. Node<T>* head;
  20. Node<T>* tail;
  21.  
  22. MyLinkedList() : head(nullptr), tail(nullptr) {}
  23.  
  24. void Add(T data)
  25. {
  26. Node<T>* newData = new Node<T>(data);
  27.  
  28. if(head == nullptr) { head = tail = newData; }
  29. else
  30. {
  31. newData->prev = tail;
  32. tail->next = newData;
  33. tail = newData;
  34. }
  35. }
  36.  
  37. void Print()
  38. {
  39. Node<int>* ptr = head;
  40. while(ptr != nullptr)
  41. {
  42. std::cout << ptr->data << "\n";
  43. ptr = ptr->next;
  44. }
  45. }
  46.  
  47. void Reverse()
  48. {
  49. // How would you implement this in O(1)?
  50. std::swap(head, tail);
  51. }
  52. };
  53.  
  54. int main() {
  55. MyLinkedList<int> list;
  56. for(int i = 1; i <= 10; ++i) list.Add(i);
  57. list.Print();
  58.  
  59. std::cout << "\nSwapping the list...\n";
  60. list.Reverse();
  61.  
  62. list.Print();
  63.  
  64. return 0;
  65. }
Success #stdin #stdout 0s 3456KB
stdin
Standard input is empty
stdout
1
2
3
4
5
6
7
8
9
10

Swapping the list...
10