0% found this document useful (0 votes)
8 views3 pages

Assignment DSA Lab

Uploaded by

fairykomal993
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views3 pages

Assignment DSA Lab

Uploaded by

fairykomal993
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 3

COMSATS UNIVERSITY ISLAMABAD, SAHIWAL CAMPUS

Assignment # 1

Submitted to Mr. Bilal Shabbir Qaisar


Submitted by Amina Arshad
Registration no SP23-BCS-190
Subject Data Structures and Algorithms
Course code CSC-211
Question #1: Use a data structure and algorithm to insert a node after a
specific value in a linked list.

#include<iostream>
using namespace std;

struct Node {
int data;
Node* next;
Node(int value) {
data = value;
next = NULL;
}
};

Node* insertAfter(Node* head, int key, int value) {

Node* ptr = head;


while (ptr != NULL) {
if (ptr->data == key)
break;
ptr = ptr->next;
}
if (ptr = = NULL)
return head;

Node* newNode = new Node(value);


newNode->next = ptr->next;
ptr->next = newNode;
return head;
}
void printList(Node* head)
{
Node* temp=head;
while(temp!=NULL){
cout<<temp->data<<"->";
temp=temp->next;
}
cout<<"NULL"<<endl;
}

int main() {
Node* head = new Node(10);
head->next = new Node(3);
head->next->next = new Node(20);
head->next->next->next = new Node(6);
int key = 3, newData = 4;

head = insertAfter(head, key, newData);

printList(head);

return 0;
}

Output:

You might also like