Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Solved Sorting Linked List in C++ #281

Merged
merged 1 commit into from
Oct 3, 2024
Merged

Conversation

pulkitgarg04
Copy link
Contributor

I have solved Sorting Linked List in C++ as per issue #280.

@AbhishekSAngadi
Copy link

#include
using namespace std;

// Node structure
struct Node {
int data;
Node* next;
Node(int x) : data(x), next(nullptr) {}
};

// Function to split the linked list into two halves
void splitList(Node* source, Node** frontRef, Node** backRef) {
Node* fast;
Node* slow;
slow = source;
fast = source->next;

// Move 'fast' two nodes and 'slow' one node
while (fast != nullptr) {
    fast = fast->next;
    if (fast != nullptr) {
        slow = slow->next;
        fast = fast->next;
    }
}

*frontRef = source;
*backRef = slow->next;
slow->next = nullptr;

}

// Function to merge two sorted lists
Node* sortedMerge(Node* a, Node* b) {
Node* result = nullptr;

// Base cases
if (a == nullptr)
    return b;
else if (b == nullptr)
    return a;

// Pick either a or b, and recur
if (a->data <= b->data) {
    result = a;
    result->next = sortedMerge(a->next, b);
} else {
    result = b;
    result->next = sortedMerge(a, b->next);
}
return result;

}

// Merge Sort function
void mergeSort(Node** headRef) {
Node* head = headRef;
Node
a;
Node* b;

// Base case: length 0 or 1
if ((head == nullptr) || (head

@Saloni6111 Saloni6111 added the hacktoberfest-accepted contribute for hacktoberfest 2024 label Oct 3, 2024
@Saloni6111 Saloni6111 merged commit fa8ee88 into Saloni6111:main Oct 3, 2024
1 check passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
hacktoberfest-accepted contribute for hacktoberfest 2024
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants