Advertisement
ruhan008

Untitled

Oct 2nd, 2023 (edited)
152
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.98 KB | None | 0 0
  1. //Q2.4) WAP to implement a linked list, update data at any position, update a value 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 InsertAtTail(node* &tail,int data){
  24.     node* newNode=(node*)malloc(sizeof(node));
  25.     newNode->setData(data);
  26.     tail->next=newNode;
  27.     tail=newNode;
  28. }
  29.  
  30. void UpdateAtPosition(node* &head,int position,int newValue){
  31.     node* temp=head;
  32.     int nodeNumber=1;
  33.     while(nodeNumber<position){
  34.         temp=temp->next;
  35.         nodeNumber++;
  36.     }
  37.     temp->data=newValue;
  38. }
  39. void UpdateTheValue(node* head,int oldValue,int newValue){
  40.     node* temp=head;
  41.     while(temp!=NULL){
  42.         if(temp->data==oldValue){
  43.             temp->data=newValue;
  44.         }
  45.         temp=temp->next;
  46.     }
  47. }
  48. void PrintLinkedList(node* &head){
  49.     node* temp=head;
  50.     while(temp!=NULL){
  51.         cout<<temp->data<<" ";
  52.         temp=temp->next;
  53.     }
  54.     cout<<endl;
  55. }
  56.  
  57. int main(){
  58.  
  59.     node* head=(node*)malloc(sizeof(node));
  60.     head->setData(1);
  61.     node* tail=head;
  62.    
  63.     InsertAtHead(head,2);
  64.     InsertAtTail(tail,4);
  65.     InsertAtTail(tail,6);
  66.  
  67.     cout<<"Before Position Updation: ";
  68.     PrintLinkedList(head);
  69.  
  70.     UpdateAtPosition(head,1,6);
  71.  
  72.     cout<<"After Position Updation: ";
  73.     PrintLinkedList(head);
  74.  
  75.     cout<<endl;
  76.  
  77.     cout<<"Before Value Updation: ";
  78.     PrintLinkedList(head);
  79.  
  80.     UpdateTheValue(head,6,7);
  81.    
  82.     cout<<"After Value Updation: ";
  83.     PrintLinkedList(head);
  84.  
  85.     return 0;
  86. }
  87. /*
  88.     OUTPUT:
  89.  
  90.     Before Position Updation: 2 1 4 6
  91.     After Position Updation: 6 1 4 6
  92.  
  93.     Before Value Updation: 6 1 4 6
  94.     After Value Updation: 7 1 4 7
  95.  
  96. */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement