Apexp3
Apexp3
Experiment 3
Student Name: Jain Aman UID: 22BCS14831
Branch: BE-CSE Section/Group: 637/B
Semester: 6th Date of Performance: 29/01/2025
Subject Name: AP LAB-II
Subject Code: 22CSP-351
Problem:01
1. Aim:
To implement and understand the merging of two sorted linked lists using an efficient
algorithm in C++.
2. Objective:
3. Implementation/Code:
class Solution {
public:
ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) {
if (!list1) return list2;
if (!list2) return list1;
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
return head->next; // Return the merged list starting from the first actual node
}
};
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
4. Output:
5. Learning Outcome:
Problem:02
1.
Aim: To remove all nodes with duplicate values from a sorted linked list, ensuring
that only distinct numbers remain in the final sorted list.
2.
Objective:
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
if (!head || !head->next) return head;
ListNode* dummy = new ListNode(0, head); // Dummy node before the head
ListNode* prev = dummy;
while (head) {
// Check if it's a start of duplicates
if (head->next && head->val == head->next->val) {
// Skip all duplicates
while (head->next && head->val == head->next->val) {
head = head->next;
}
prev->next = head->next; // Remove duplicates
} else {
prev = prev->next; // Move forward
}
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
4. Output:
5. Learning Outcome:
• Understand how to detect and remove duplicate nodes from a sorted linked list.
• Implement pointer manipulation for modifying linked lists efficiently.
• Optimize space and time complexity for duplicate removal operations.
• Develop problem-solving skills in linked list-based challenges.
• Improve coding proficiency for technical interviews and competitive
programming.
DEPARTMENT OF