Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //Q2.4) WAP to implement a linked list, update data at any position, update a value and then print the linked list.
- #include <iostream>
- #include<stdlib.h>
- using namespace std;
- struct node{
- int data;
- node* next;
- void setData(int d){
- data=d;
- next=NULL;
- }
- };
- void InsertAtHead(node* &head,int data){
- node* newNode=(node*)malloc(sizeof(node));
- newNode->setData(data);
- newNode->next=head;
- head=newNode;
- }
- void InsertAtTail(node* &tail,int data){
- node* newNode=(node*)malloc(sizeof(node));
- newNode->setData(data);
- tail->next=newNode;
- tail=newNode;
- }
- void UpdateAtPosition(node* &head,int position,int newValue){
- node* temp=head;
- int nodeNumber=1;
- while(nodeNumber<position){
- temp=temp->next;
- nodeNumber++;
- }
- temp->data=newValue;
- }
- void UpdateTheValue(node* head,int oldValue,int newValue){
- node* temp=head;
- while(temp!=NULL){
- if(temp->data==oldValue){
- temp->data=newValue;
- }
- temp=temp->next;
- }
- }
- void PrintLinkedList(node* &head){
- node* temp=head;
- while(temp!=NULL){
- cout<<temp->data<<" ";
- temp=temp->next;
- }
- cout<<endl;
- }
- int main(){
- node* head=(node*)malloc(sizeof(node));
- head->setData(1);
- node* tail=head;
- InsertAtHead(head,2);
- InsertAtTail(tail,4);
- InsertAtTail(tail,6);
- cout<<"Before Position Updation: ";
- PrintLinkedList(head);
- UpdateAtPosition(head,1,6);
- cout<<"After Position Updation: ";
- PrintLinkedList(head);
- cout<<endl;
- cout<<"Before Value Updation: ";
- PrintLinkedList(head);
- UpdateTheValue(head,6,7);
- cout<<"After Value Updation: ";
- PrintLinkedList(head);
- return 0;
- }
- /*
- OUTPUT:
- Before Position Updation: 2 1 4 6
- After Position Updation: 6 1 4 6
- Before Value Updation: 6 1 4 6
- After Value Updation: 7 1 4 7
- */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement