fork download
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3.  
  4. //Node using class
  5.  
  6. class Node{
  7. public:
  8. int data;
  9. Node* next;
  10.  
  11. Node(int data, Node* next = nullptr){
  12. this->data = data;
  13. this->next = next;
  14. }
  15. };
  16.  
  17.  
  18. int main(){
  19. //Create Nodes
  20. Node* node1 = new Node(5);
  21. Node* node2 = new Node(6);
  22. Node* node3 = new Node(7);
  23. Node* node4 = new Node(8);
  24.  
  25. //Create links
  26.  
  27. Node* head = node1;
  28. node1->next=node2;
  29. node2->next=node3;
  30. node3->next=node4;
  31.  
  32.  
  33. //print the list
  34. cout<<"First List: "<<endl;
  35. while(head != NULL){
  36.  
  37. cout<<head->data<<endl;
  38.  
  39. head = head->next;
  40.  
  41. }
  42.  
  43.  
  44. //Create a list dynamically
  45. Node* newNode = new Node(1);
  46. Node* newList = newNode;
  47. Node* newhead = newNode;
  48.  
  49. int i=2;
  50. while(i<20){
  51. Node* temp = new Node(i);
  52. newList->next = temp;
  53. newList = newList->next;
  54. i++;
  55.  
  56. }
  57. cout<<"Second List:"<<endl;
  58. //Print the list
  59. while(newhead != nullptr){
  60. cout<<newhead->data<<endl;
  61. newhead= newhead->next;
  62. }
  63. }
Success #stdin #stdout 0.01s 5284KB
stdin
Standard input is empty
stdout
First List: 
5
6
7
8
Second List:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19