Advertisement
ruhan008

Untitled

Oct 2nd, 2023 (edited)
137
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.95 KB | None | 0 0
  1. //Q2.1) WAP to implement a linked list, insert data at the end and then print the linked list.
  2.  
  3. #include <iostream>
  4. #include<stdlib.h>
  5. using namespace std;
  6.  
  7. struct node{
  8.     int data;
  9.     node* next;
  10.     void setData(int d){
  11.         data=d;
  12.         next=NULL;
  13.     }
  14. };
  15.  
  16. void InsertAtTail(node* &tail,int data){
  17.     node* newNode=(node*)malloc(sizeof(node));
  18.     newNode->setData(data);
  19.     tail->next=newNode;
  20.     tail=newNode;
  21. }
  22. void PrintLinkedList(node* &head){
  23.     node* temp=head;
  24.     while(temp!=NULL){
  25.         cout<<temp->data<<" ";
  26.         temp=temp->next;
  27.     }
  28.     cout<<endl;
  29. }
  30.  
  31. int main(){
  32.  
  33.     node* head=(node*)malloc(sizeof(node));
  34.     head->setData(1);
  35.     node* tail=head;
  36.  
  37.     InsertAtTail(tail,2);
  38.     InsertAtTail(tail,3);
  39.     InsertAtTail(tail,4);
  40.     InsertAtTail(tail,5);
  41.  
  42.     cout<<"After Insertion: ";
  43.     PrintLinkedList(head);
  44.  
  45.     return 0;
  46. }
  47. /*
  48.     OUTPUT:
  49.  
  50.     After Insertion: 1 2 3 4 5
  51.  
  52. */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement