fork download
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. ///------------ CREATE NODE CLASS---------
  4. class Node{
  5. public:
  6. int data;
  7. Node *next;
  8.  
  9. Node(int x=0){
  10. this->data = x;
  11. this->next = nullptr; /// NULL
  12. }
  13. };
  14. ///------------ CREATE LINKED LIST CLASS ---------
  15. class LinkedList{
  16. private:
  17. Node *HEAD;
  18. public:
  19. LinkedList(){
  20. HEAD = nullptr;
  21. }
  22. /// insert a new element at the first position of the linked list
  23. void insertAtFirst(int x){
  24. Node *newNode = new Node(x);
  25. newNode->next = HEAD;
  26. HEAD = newNode;
  27. }
  28. /// display the elements in the linked list
  29. void display(){
  30. if(HEAD==nullptr){
  31. cout<<"The list is empty"<<endl;
  32. return;
  33. }
  34. Node *currentNode = HEAD;
  35. while(currentNode!=nullptr){
  36. cout<< currentNode->data <<"->";
  37. currentNode = currentNode->next;
  38. }
  39. cout<< "NULL" << endl;
  40. }
  41.  
  42. ///-------Insert a new node as the last node---------
  43. void insertAtLast( int x ) {
  44. Node *newNode = new Node (x); /// create new node
  45. if (HEAD==nullptr) {
  46. HEAD = newNode ;
  47. return;
  48. }
  49. Node*currentNode = HEAD ;
  50. while (currentNode->next != nullptr) {
  51. currentNode = currentNode->next;
  52. }
  53. currentNode->next = newNode;
  54. }
  55. };
  56.  
  57.  
  58. ///-------------- MAIN FUNCTION ------------
  59. int main()
  60. {
  61. LinkedList myList;
  62.  
  63. myList.insertAtLast(30);
  64. myList.insertAtLast(50);
  65. myList.insertAtLast(100);
  66.  
  67. myList.display();
  68.  
  69. return 0;
  70. }
Success #stdin #stdout 0.01s 5328KB
stdin
Standard input is empty
stdout
30->50->100->NULL