fork download
  1. #include <iostream>
  2. #include <vector>
  3. #include <sstream>
  4. #include <queue>
  5.  
  6. class Node
  7. {
  8. public:
  9. Node(std::string name) :
  10. name_(name)
  11. {}
  12. ~Node()
  13. {
  14. for (Node* child : children_)
  15. {
  16. delete child;
  17. }
  18. children_.clear();
  19. }
  20. void addChild(Node* child)
  21. {
  22. children_.push_back(child);
  23. }
  24. bool hasChild(const std::string name)
  25. {
  26. for (Node* child : children_)
  27. {
  28. if (child->getName() == name)
  29. {
  30. return true;
  31. }
  32. }
  33. return false;
  34. }
  35. std::string getName() const
  36. {
  37. return name_;
  38. }
  39. std::vector<Node*> getChildren() const
  40. {
  41. return children_;
  42. }
  43. Node* getChild(const std::string name) const
  44. {
  45. for (Node* child : children_)
  46. {
  47. if (child->getName() == name)
  48. {
  49. return child;
  50. }
  51. }
  52. return nullptr;
  53. }
  54.  
  55. void printChildren(int level)
  56. {
  57. for (Node* child : children_)
  58. {
  59. for (int i = 0; i < level; i++)
  60. {
  61. std::cout << ' ';
  62. }
  63. std::cout << child->getName() << std::endl;
  64. child->printChildren(level + 1);
  65. }
  66. }
  67. private:
  68. std::string name_;
  69. std::vector<Node*> children_;
  70. };
  71. class FileSys
  72. {
  73. public:
  74. FileSys() :
  75. root_(new Node(""))
  76. {}
  77. ~FileSys()
  78. {
  79. delete root_;
  80. }
  81. void add(std::vector<std::string> paths)
  82. {
  83. for (std::string path : paths)
  84. {
  85. std::stringstream ss(path);
  86. std::string dir;
  87. std::queue<std::string> dirs;
  88. while (std::getline(ss, dir, '/'))
  89. {
  90. dirs.push(dir);
  91. }
  92. dirs.pop();
  93. Node* parent = root_;
  94. while (!dirs.empty())
  95. {
  96. Node* current = new Node(dirs.front());
  97. if (!parent->hasChild(dirs.front()))
  98. {
  99. parent->addChild(current);
  100. parent = current;
  101. }
  102. else
  103. {
  104. parent = parent->getChild(dirs.front());
  105. }
  106. dirs.pop();
  107. }
  108. }
  109. }
  110. Node* getRoot() const
  111. {
  112. return root_;
  113. }
  114. void print()
  115. {
  116. root_->printChildren(0);
  117. }
  118. private:
  119. Node* root_;
  120. };
  121.  
  122. int main(int argc, char** argv)
  123. {
  124. std::vector<std::string> vec;
  125. vec.push_back("/Users/Vlad/my/file");
  126. vec.push_back("/bin/bash");
  127. vec.push_back("/usr/local/bin");
  128. vec.push_back("/usr/local/lib");
  129.  
  130. FileSys fileSys;
  131. fileSys.add(vec);
  132. fileSys.print();
  133.  
  134. return 0;
  135. }
Success #stdin #stdout 0s 16080KB
stdin
Standard input is empty
stdout
Users
 Vlad
  my
   file
bin
 bash
usr
 local
  bin
  lib