Advertisement
ruhan008

Untitled

Oct 2nd, 2023
136
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.93 KB | None | 0 0
  1. //Q2.2) WAP to implement a linked list, insert data at the front 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 InsertAtHead(node* &head,int data){
  17.     node* newNode=(node*)malloc(sizeof(node));
  18.     newNode->setData(data);
  19.     newNode->next=head;
  20.     head=newNode;
  21. }
  22.  
  23. void PrintLinkedList(node* &head){
  24.     node* temp=head;
  25.     while(temp!=NULL){
  26.         cout<<temp->data<<" ";
  27.         temp=temp->next;
  28.     }
  29.     cout<<endl;
  30. }
  31.  
  32. int main(){
  33.  
  34.     node* head=(node*)malloc(sizeof(node));
  35.     head->setData(1);
  36.  
  37.     InsertAtHead(head,2);
  38.     InsertAtHead(head,3);
  39.     InsertAtHead(head,4);
  40.     InsertAtHead(head,5);
  41.  
  42.     cout<<"After Insertion: ";
  43.     PrintLinkedList(head);
  44.  
  45.     return 0;
  46. }
  47. /*
  48.     OUTPUT:
  49.  
  50.     After Insertion: 5 4 3 2 1
  51.  
  52. */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement