fork download
  1. #include <iostream>
  2.  
  3. struct Node {
  4. int data_;
  5. Node* next_ { nullptr };
  6. Node* prev_ { nullptr };
  7.  
  8. Node(int data) : data_(data) {}
  9. };
  10.  
  11.  
  12. struct DLL {
  13. Node* head_ { nullptr };
  14. Node* tail_ { nullptr };
  15. int size_ { 0 };
  16.  
  17. //Adding a Node to the Doubly LL
  18. void addNode(Node* node) {
  19. //If LL is empty add the first Node
  20. if (tail_ == nullptr) {
  21. tail_ = node;
  22. head_ = node;
  23. node->prev_ = node->next_ = nullptr;
  24. }
  25. //Else add add node to the tail. Connect n to the tails next and make n the tail
  26. else {
  27. tail_->next_ = node;
  28. node->prev_ = tail_;
  29. tail_ = node;
  30. node->next_ = nullptr;
  31. }
  32.  
  33. size_++;
  34. }
  35.  
  36. //Finding a random Node in the linked List
  37. //It will return the Node with the FIRST occurrence where data = d
  38. Node* findNode(int data) const {
  39. //We will start at the head and then traverse through the entire list to find a Node where data = d
  40. //While next pointer is not null, traverse to search for a match.s
  41. for (Node* start = head_; start != nullptr; start = start->next_) {
  42. if (start->data_ == data) {
  43. std::cout << "Node found with matching data : " << start << '\n';
  44. return start;
  45. }
  46. }
  47.  
  48. std::cout << "No node found with matching data = " << data << '\n';
  49. return nullptr;
  50. }
  51. };
  52.  
  53. int main()
  54. {
  55. DLL dll;
  56.  
  57. Node n1(1), n3(3), n5(5);
  58. dll.addNode(&n1);
  59. dll.addNode(&n3);
  60. dll.addNode(&n5);
  61.  
  62. if (dll.findNode(1) != &n1)
  63. std::cerr << "wrong result for findNode(1)\n";
  64. if (dll.findNode(2) != nullptr)
  65. std::cerr << "wrong result for findNode(2)\n";
  66. if (dll.findNode(3) != &n3)
  67. std::cerr << "wrong result for findNode(3)\n";
  68. if (dll.findNode(4) != nullptr)
  69. std::cerr << "wrong result for findNode(4)\n";
  70. if (dll.findNode(5) != &n5)
  71. std::cerr << "wrong result for findNode(5)\n";
  72. }
Success #stdin #stdout 0s 3468KB
stdin
Standard input is empty
stdout
Node found with matching data : 0xffabebec
No node found with matching data = 2
Node found with matching data : 0xffabebf8
No node found with matching data = 4
Node found with matching data : 0xffabec04