Skip to content

Commit

Permalink
Merge pull request #1823 from SKG24/main
Browse files Browse the repository at this point in the history
added merge two sorted list #1805
  • Loading branch information
ajay-dhangar authored Nov 5, 2024
2 parents 0eb9715 + d71fa1b commit 8531024
Show file tree
Hide file tree
Showing 2 changed files with 202 additions and 0 deletions.
82 changes: 82 additions & 0 deletions docs/linked-list/merge-two-sorted-list.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
---
id: merge-two-sorted-list
sidebar_position: 1
title: "Merge Two Sorted Linked Lists"
description: "This tutorial explains how to merge two sorted list using Cpp."
sidebar_label: "Linked List Intersection"
tags: [dsa, linked-lists, merge,cpp]
---
# Merge Two Sorted Linked Lists

## Problem Statement

Given two sorted linked lists, the task is to merge them into one sorted linked list. The merged linked list should be created by splicing together the nodes of the input lists.

### Example

**Input:**
- `list1 = [1, 2, 4]`
- `list2 = [1, 3, 4]`

**Output:**
- `Merged List: 1 -> 1 -> 2 -> 3 -> 4 -> 4`

### Constraints
- Both lists are sorted in non-decreasing order.
- The output should maintain the sorted order by merging nodes directly from the input lists.

## Solution Explanation

To merge the two sorted linked lists:
1. **Dummy Node and Tail**: Start with a dummy node to simplify list manipulation. Use a `tail` pointer to keep track of the last node in the merged list.
2. **Comparison and Insertion**:
- Traverse both lists. For each pair of nodes from the two lists, attach the smaller node to the `tail` and move to the next node in that list.
3. **Remaining Nodes**:
- Once one list is exhausted, link the rest of the nodes from the remaining list to the `tail`.
4. **Return Merged List**:
- The merged list starts from `dummy.next` since `dummy` is just a placeholder.

### Complexity
- **Time Complexity**: `O(n + m)`, where `n` and `m` are the lengths of the two input lists.
- **Space Complexity**: `O(1)` (in-place merging without additional data structures).

## Code Implementation

Here’s the C++ code for merging two sorted linked lists:

```cpp
#include <iostream>
#include<vector>
using namespace std;

struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(nullptr) {}
};

class Solution {
public:
ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) {
ListNode dummy(0); // Dummy node to start the merged list
ListNode* tail = &dummy;

// Merge the lists by comparing nodes
while (list1 && list2) {
if (list1->val < list2->val) {
tail->next = list1;
list1 = list1->next;
} else {
tail->next = list2;
list2 = list2->next;
}
tail = tail->next;
}

// Attach the remaining nodes, if any
tail->next = list1 ? list1 : list2;

return dummy.next; // Return the head of the merged list
}
};
```
120 changes: 120 additions & 0 deletions docs/linked-list/remove-duplicates-from-sorted-list.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
---
id: remove-duplicates-from-sorted-list
sidebar_position: 1
title: "Remove Duplicates from Sorted Linked Lists"
description: "This tutorial explains how to remove duplicates from sorted list using Cpp."
sidebar_label: "Linked List Intersection"
tags: [dsa, linked-lists,cpp]
---

# Remove Duplicates from Sorted List

## Problem Statement

Given the head of a sorted linked list, remove all duplicates such that each element appears only once. Return the modified linked list, which remains sorted.

### Example

**Input:**
- `head = [1,1,2]`

**Output:**
- `[1,2]`

### Constraints
- The list is sorted in non-decreasing order.
- The output should retain the sorted order with no duplicate values.

## Solution Explanation

To remove duplicates from the sorted linked list:
1. **Single Pass with Current Pointer**:
- Use a pointer (`current`) to traverse the list.
- At each node, compare the value of `current` with `current->next`.
- If the values are the same, update the `next` pointer of `current` to skip the duplicate node.
- If the values are different, move `current` to the next node.
2. **End Condition**:
- Continue the process until `current` reaches the end of the list.
3. **In-place Modification**:
- This algorithm modifies the list in place without additional data structures.

### Complexity
- **Time Complexity**: `O(n)`, where `n` is the number of nodes in the linked list, as we traverse each node once.
- **Space Complexity**: `O(1)`, as it operates in constant space by modifying the list in place.

## Code Implementation

Here’s the C++ code for removing duplicates from a sorted linked list:

```cpp
#include <iostream>
#include<vector>
using namespace std;

struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(nullptr) {}
};

class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
if (!head) return nullptr; // If list is empty, return null

ListNode* current = head; // Start with the head of the list

// Traverse the list
while (current && current->next) {
if (current->val == current->next->val) {
// Skip the duplicate node
ListNode* duplicate = current->next;
current->next = duplicate->next;
delete duplicate; // Free memory for the duplicate node
} else {
// Move to the next distinct element
current = current->next;
}
}

return head; // Return the modified list without duplicates
}
};

// Helper function to create a linked list from an array
ListNode* createLinkedList(const vector<int>& values) {
ListNode dummy(0);
ListNode* current = &dummy;
for (int value : values) {
current->next = new ListNode(value);
current = current->next;
}
return dummy.next;
}

// Helper function to print a linked list
void printLinkedList(ListNode* head) {
while (head) {
cout << head->val;
if (head->next) cout << " -> ";
head = head->next;
}
cout << endl;
}

int main() {
vector<int> list_values = {1, 1, 2};
ListNode* head = createLinkedList(list_values);

cout << "Original List: ";
printLinkedList(head);

Solution solution;
ListNode* modifiedHead = solution.deleteDuplicates(head);

cout << "List after removing duplicates: ";
printLinkedList(modifiedHead);

return 0;
}
```

0 comments on commit 8531024

Please sign in to comment.