fork download
  1. #include <iostream>
  2. #include <cstring>
  3.  
  4. using std::cout;
  5. using std::endl;
  6.  
  7. class Node {
  8.  
  9. int data;
  10. Node* next;
  11.  
  12. public:
  13.  
  14. Node() { };
  15. void SetData(int aData) { data = aData; };
  16. void SetNext(Node* aNext) { next = aNext; };
  17. int Data() { return data; };
  18. Node* Next() { return next; };
  19. };
  20.  
  21. class List {
  22.  
  23. Node *head;
  24.  
  25. public:
  26.  
  27. List() : head(NULL) { };
  28. void Print();
  29. void Append(int data);
  30. void Delete(int data);
  31. };
  32.  
  33. void List::Append(int data) {
  34.  
  35. // Create a new node
  36. Node* newNode = new Node();
  37. newNode->SetData(data);
  38. newNode->SetNext(NULL);
  39.  
  40. // Create a temp pointer
  41. Node *tmp = head;
  42.  
  43. if ( tmp ) {
  44. if ( tmp->Data() > newNode->Data() ) {
  45. newNode->SetNext(tmp);
  46. head = newNode;
  47. }
  48. else {
  49. // Nodes already present in the list
  50. // Parse to end of list anytime the next data has lower value
  51. while ( tmp->Next() && tmp->Next()->Data() <= newNode->Data() ) {
  52. tmp = tmp->Next();
  53. }
  54.  
  55. // Point the lower value node to the new node
  56. Node* _next = tmp->Next();
  57. tmp->SetNext(newNode);
  58. newNode->SetNext(_next);
  59. }
  60. }
  61. else {
  62. // First node in the list
  63. head = newNode;
  64. }
  65. }
  66.  
  67. void List::Print() {
  68.  
  69. // Temp pointer
  70. Node *tmp = head;
  71.  
  72. // No nodes
  73. if ( !tmp ) {
  74. cout << "EMPTY" << endl;
  75. return;
  76. }
  77.  
  78. // One node in the list
  79. if ( !tmp->Next() ) {
  80. cout << tmp->Data();
  81. cout << " --> ";
  82. cout << "NULL" << endl;
  83. }
  84. else {
  85. // Parse and print the list
  86. do {
  87. cout << tmp->Data();
  88. cout << " --> ";
  89. tmp = tmp->Next();
  90. }
  91. while ( tmp );
  92.  
  93. cout << "NULL" << endl;
  94. }
  95. }
  96.  
  97. int main() {
  98. List l;
  99. l.Append(15);
  100. l.Append(40);
  101. l.Append(7);
  102. l.Print();
  103. return 0;
  104. }
Success #stdin #stdout 0.02s 2856KB
stdin
Standard input is empty
stdout
7 --> 15 --> 40 --> NULL