Question

Could anyone help me solve this problem in C++? Write a function that sorts a linked...

Could anyone help me solve this problem in C++?

Write a function that sorts a linked list. (Use any sort algorithm, make sure to state which one your going to use.)

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Solution : Using Merge Sort to sort a given linked list.

Code :

#include <bits/stdc++.h>
using namespace std;


class Node {
public:
int data;
Node* next;
};

/* utility functions */

Node* SortedList(Node* a, Node* b);

void Split(Node* source,Node** start, Node** end);

/* sorting the linked list by changing next pointers (not data) */
void mergeSort(Node** dummyHead)
{
Node* head = *dummyHead;
Node* a;
Node* b;

/* Base case -- length 0 or 1 */
if ((head == NULL) || (head->next == NULL)) {
return;
}

/* Split head into 'a' and 'b' sublists */
Split(head, &a, &b);

/* Recursively sorting the sublists */
mergeSort(&a);
mergeSort(&b);

/* merging the two sorted lists together */
*dummyHead = SortedList(a, b);
}


Node* SortedList(Node* a, Node* b)
{
Node* result = NULL;

/* Base case */
if (a == NULL)
return (b);
else if (b == NULL)
return (a);


if (a->data <= b->data) {
result = a;
result->next = SortedList(a->next, b);
}
else {
result = b;
result->next = SortedList(a, b->next);
}
return (result);
}

/* Splitting the nodes of the list into two halves i.e starting and ending and returning the lists using reference parameters. */
void Split(Node* source,Node** start, Node** end)
{
Node* fast;
Node* slow;
slow = source;
fast = source->next;

/* increment 'fast' two nodes, and advance 'slow' one node */
while (fast != NULL) {
fast = fast->next;
if (fast != NULL) {
slow = slow->next;
fast = fast->next;
}
}

/* if 'slow' is before the midpoint in the list, we split it in two
at that point. */
*start = source;
*end = slow->next;
slow->next = NULL;
}

/* printing nodes of the linked list*/
void printList(Node* node)
{
while (node != NULL) {
cout << node->data << " ";
node = node->next;
}
}

/* inserting node at the beginning of the linkedlist */
void push(Node** dummy_head, int new_data)
{
/* allocate node */
Node* new_node = new Node();

/* put in the data */
new_node->data = new_data;

/* link the old list off the new node */
new_node->next = (*dummy_head);

/* move the head to point to the new node */
(*dummy_head) = new_node;
}


int main()
{
/* Starting with an empty list */
Node* res = NULL;
Node* a = NULL;

/*pushing elements in the linked list*/
push(&a, 13);
push(&a, 8);
push(&a, 4);
push(&a, 18);
push(&a, 6);
push(&a, 1);

/* Sorting the linkedlist*/
mergeSort(&a);

cout << "Sorted Linked List : \n";
printList(a);

return 0;
}

#include bits/stdc++.h> using namespace std; Çclass Node { public: int data; Node* next; Ll: 4 4 /* utility functions / Noderesult = a; result->next = SortedList (a->next, b); else { result = b; result->next = SortedList(a, b->next); return (result)new_node->data = new_data; /* link the old list off the new node */ new_node->next = (durmy_head); /* move the head to point

Output :

Sorted Linked List : 1 4 6 8 13 18 Process returned 0 (0x0_ Press any key to continue. execution time: 0.013 s

Add a comment
Know the answer?
Add Answer to:
Could anyone help me solve this problem in C++? Write a function that sorts a linked...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Could anyone help me solve this problem in C++? Thanks a lot. Develop an OOP program...

    Could anyone help me solve this problem in C++? Thanks a lot. Develop an OOP program to maintain a list of homework assignments. When an assignment is assigned, add it to the list, and when it is completed, remove it. You should keep track of the due date. Your program should provide the following services: • Add a new assignment. • Remove an assignment. • Provide a list of the assignments in the order they were assigned. • Find the...

  • it is c programming problem. help me to do this problem 1. write a insertion function...

    it is c programming problem. help me to do this problem 1. write a insertion function and deletion function for a double-linked list

  • Could anyone help me solve this C++ problem? Thanks a lot create a class called minHeap...

    Could anyone help me solve this C++ problem? Thanks a lot create a class called minHeap to demonstrate the min Heap data structure of type integer. use a vector to implement the concept. in this class, have the following: private: vector of the type integer integer to store the index of the last element in the min heap "vector" integer to store the size (number of items in the vector "min heap") public: default constructor to set the size to...

  • This is a c++ code /**    Write a function sort that sorts the elements of...

    This is a c++ code /**    Write a function sort that sorts the elements of a std::list without using std::list::sort or std::vector. Instead use list<int>::iterator(s) */ using namespace std; #include <iostream> #include <iomanip> #include <string> #include <list> void print_forward (list<int>& l) { // Print forward for (auto value : l) { cout << value << ' '; } cout << endl; } void sort(list<int>& l) { write code here -- do not use the built-in list sort function }...

  • Write a Python function to implement the quick sort algorithm over a singly linked list. The...

    Write a Python function to implement the quick sort algorithm over a singly linked list. The input of your function should be a reference pointing to the first node of a linked list, and the output of your function should also be a reference to the first node of a linked list, in which the data have been sorted into the ascending order. (You may use the LinkedQueue class we introduced in the lecture directly in your program.)

  • I need help with encoding a doubly-linked list, which must include a function that sorts the...

    I need help with encoding a doubly-linked list, which must include a function that sorts the name field in the bubble method, it must be encoded in the c language.

  • Can anyone help me to solve this problem? Thanks in advance Assignment 6 Strings Write a...

    Can anyone help me to solve this problem? Thanks in advance Assignment 6 Strings Write a program which makes Caesar encryption. Caesar encryption is based on circular shifting of the letters with a given amount. Your program will encrypt the input and it will shift the letters by the given amount (if it passes z, it will continue from a), it will not change spaces (" "). You can assume that no other characters will be entered.

  • This is a c programming problem. Would you please help me to write this problem??? I...

    This is a c programming problem. Would you please help me to write this problem??? I really appreciate it if you add comments for explanation step by step. Thank you. Reverse a Doubly linked list using recursion: Given a doubly linked list. Reverse it using recursion. Original Doubly linked list: next pointer - DDHIHI Null prev painter Reversed Doubly linked list: next pointer Start Pointer Null prev pointer Include: a) A struct for a node of the doubly linked list....

  • SOS!!!! Anyone can help me solve this problem?

    SOS!!!! Anyone can help me solve this problem?

  • Create MIPS program that sorts positive numbers. Inputs the numbers until a zero is inputted and the program displays the sorted numbers. Can use any sorting algorithm except bubble sort.

    Write a MIPS assembly program that sorts a sequence of positive integersentered from the console (one number in one line). The end of thesequence is indicated by a 0 (zero). Verify that the program is correct bysimulation. You can use any sorting algorithm in your code except bubblesort, such as selection sort, merge sort, quick sort, etc. There must be aprocedure call as well as looping in your code. use recursive procedurecalls instead of looping to solve the same problem....

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT