Advertisement
ruhan008

Untitled

Oct 2nd, 2023 (edited)
153
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.01 KB | Source Code | 0 0
  1. //Q1) WAP to implement a linked list with three nodes to accept data at those nodes
  2. //and then display the nodes.
  3.  
  4. #include <iostream>
  5. #include<stdlib.h>
  6. using namespace std;
  7.  
  8. struct node{
  9.     int data;
  10.     node* next;
  11.     void setData(int d){
  12.         data=d;
  13.         next=NULL;
  14.     }
  15. };
  16.  
  17. int main(){
  18.  
  19.     node* node1=(node*)malloc(sizeof(node));
  20.     node1->setData(10);
  21.     node* node2=(node*)malloc(sizeof(node));
  22.     node2->setData(20);
  23.     node* node3=(node*)malloc(sizeof(node));
  24.     node3->setData(30);
  25.  
  26.     node1->next=node2;
  27.     node2->next=node3;
  28.  
  29.     node* temp=node1;
  30.     int nodeNumber=1;
  31.     while(nodeNumber<=3){
  32.         cout<<"Node: "<<nodeNumber<<endl;
  33.         cout<<"Address: "<<temp->next<<", Data: "<<temp->data<<endl;
  34.         temp=temp->next;
  35.         nodeNumber++;
  36.     }
  37.     cout<<endl;
  38.  
  39.     return 0;
  40. }
  41. /*
  42.     OUTPUT:
  43.    
  44.     Node: 1
  45.     Address: 0x5557701cf2d0, Data: 10
  46.     Node: 2
  47.     Address: 0x5557701cf2f0, Data: 20
  48.     Node: 3
  49.     Address: 0, Data: 30
  50.  
  51. */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement