Question

5.8 Sort Linked List Use mergersort to sort a linked list Do not use the following...

5.8 Sort Linked List

Use mergersort to sort a linked list Do not use the following libraries: algorithm, cmath. Do not load the values into a vector and sort them. The sort must be done with a linked list
Example
Two lists 6->3->1->2->4->5 will return a list with 1->2->3->4->5->6.
Input
There will be no input read in anymore. Going forward use the hard-coded input on the template and ensure the program works. There will be one compare output test based on the hard-coded input. The rest of the tests will be unit tests.
Output
Print out the newly returned list. Just print out the integers separated by a space.

#include <iostream>

#include <vector>

// DO NOT MODIFY

struct Node {

    int val;

    Node * next;

    Node( int num ){

        val = num;

        next = nullptr;

    }

};

// DO NOT MODIFY

Node * createList( std::vector<int> & vec ){

    int i = 0;

    Node * head = new Node( vec[i++] );

    Node * runner = head;

    for( i; i < vec.size(); i++ ){

        Node * temp = new Node( vec[i] );

        runner->next = temp;

        runner = runner->next;

    }

    

    return head;

}

    Node* mergeTwoLists(Node* l1, Node* l2) {

        // Use your mergeTwoLists function from last week

    }

    

    Node * mergeSort( Node * head ){

        /* Follow merge sort. The tricky part is spliting the lists in half at each step correctly.

        If you are not confident, draw out how you could split each list in half till you hit a base case.

        */

    }

    

    

int main(){

   // Just concentrate on the function

   std::vector<int> values{ 6, 3, 1, 2, 4, 5};

   

   Node * list = createList( values );

   

   list = mergeSort( list );

   

   while( list ){

      std::cout << list->val << " ";

      list = list->next;

   }

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

Answer:-

code:

 #include <iostream>
#include <vector>
// DO NOT MODIFY
struct Node
{
    int val;
    Node * next;
    Node( int num )
    { val = num; 
    next = NULL; }
};
    // DO NOT MODIFY
Node * createList( std::vector<int> & vec )
{
    int i = 0; 
    Node * head = new Node( vec[i++] );
    Node * runner = head;
    for( i; i < vec.size(); i++ )
    {
        Node * temp = new Node( vec[i] );
        runner->next = temp;
        runner = runner->next;
    }
    return head;
}
Node* mergeTwoLists(Node* l1, Node* l2)
{
    // Use your mergeTwoLists function from last week
    struct Node* temp1=l1,*temp2=l2,*head,*temp,*hemp;       //temporary variables 
    /* for assigning head for new merged list */
    if(temp1->val<=temp2->val)
    { 
        temp=temp1->next;
        head=temp1;
        if(temp1!=NULL)
        temp1->next=NULL;
        temp1=temp;
    } 
    else
    {
        temp=temp2->next;
        head=temp2;
        if(temp2!=NULL) 
        temp2->next=NULL;
        temp2=temp;
    }
    hemp=head;        //storing new head in a temporary variable for iteration 
    /*upto here*/ 
    /*here merging rest of the list*/ 
    while(temp1!=NULL && temp2!=NULL )
    {
        if(temp1->val<temp2->val)
        {
            temp=temp1->next;
            hemp->next=temp1;
            if(temp1!=NULL)
            temp1->next=NULL;
            temp1=temp;
            hemp=hemp->next;
        }
        else
        {
            temp=temp2->next;
            hemp->next=temp2;
            if(temp2!=NULL)
            temp2->next=NULL;
            temp2=temp;
            hemp=hemp->next;
        }
    }
    while(temp1!=NULL)
    { 
        temp=temp1->next;
        hemp->next=temp1;
        if(temp1!=NULL)
        temp1->next=NULL;
        temp1=temp;
        hemp=hemp->next;
    }
    while(temp2!=NULL)
    {
        temp=temp2->next;
        hemp->next=temp2;
        if(temp2!=NULL)
        temp2->next=NULL;
        temp2=temp;
        hemp=hemp->next;
    } 
    return head;
}
Node * mergeSort( Node * head )
{
    /* Follow merge sort.
    The tricky part is spliting the lists in half at each step correctly
    . If you are not confident, draw out how you could split each list in half till you hit a base case. */
    if (head==NULL||head->next==NULL)
    return head;
    /* split the list by finding mid using slow& fast pointers*/
    struct Node *s=head;
    struct Node *f=head;
    struct Node *temp;
    while(1)
    {
        if(f->next==NULL||f->next->next==NULL)
        break;
        else
        {
            f=f->next->next;
            s=s->next;
        }
    }
    temp=s->next;
    s->next=NULL;
    /*upto here*/
    head = mergeSort(head);
    temp = mergeSort(temp);
    /* calling the merge function */
    Node* merged_head= mergeTwoLists(head,temp);
    return merged_head;
}
int main()
{
    // Just concentrate on the function
    std::vector<int> values{ 6, 3, 1, 2, 4, 5};
    Node * list = createList( values );
    list = mergeSort( list );
    while( list )
    {
        std::cout << list->val << " ";
        list = list->next;
    }
}

output:

Please upvote if you like the answer!

Run Debug Stop Share A Save {}Beautify Language C++ 14 @ main.cpp CO if(temp2!=NULL) temp 2->next=NULL; temp2=temp; hemp=hemp->next; while(temp1!=NULL) 600 OU WN 99 100 temp=temp 1 ->next; hemp->next=temp1; if(temp1!=NULL) temp 1->next=NULL; temp1=temp; hemp=hemp->next; 101 102 103 while(temp2!=NULL) 104 - 105 106 107 108 109 110 111 112 temp=temp 2 ->next; hemp->next=temp2; if(temp2!=NULL) temp 2 ->next=NULL; temp2=temp; hemp=hemp->next; return head; 113 114 115 input 1 2 3 4 5 6 ... Program finished with exit code o Press ENTER to exit console. Activate Windows Go to Settings to activate Windo

Add a comment
Know the answer?
Add Answer to:
5.8 Sort Linked List Use mergersort to sort a linked list Do not use the following...
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
  • I am losing elements when I sort my Linked List. How can I sort my Linked...

    I am losing elements when I sort my Linked List. How can I sort my Linked list in alphabetical order? Code: void sort(Node *head) { Node* temp = head; Node* tempAhead = temp -> next; Node* buff1 = temp; Node* buff2 = tempAhead; while (temp -> next != NULL) { while (tempAhead -> next != NULL) { if (strcmp(temp -> name, tempAhead -> name) < 0) { buff1 -> next = temp -> next; buff2 -> next = tempAhead ->...

  • this is i have code for double linked list with insert at sorted list. i have...

    this is i have code for double linked list with insert at sorted list. i have some error that stdout: ------- Error: compilation stderr: ------- InsertDouble.c: In function ‘list* InsertDouble(LIST, int)’: InsertDouble.c:51:14: error: cannot convert ‘list’ to ‘list*’ in assignment Currentptr = *head; // set a pointer which is current one ^ it keep give me this error i am not sure how to fix is anyone possible to help me? #include <stdio.h> #include <stdlib.h> typedef struct list {   ...

  • Write a C++ function to add a node to the beginning of a linked list. Your...

    Write a C++ function to add a node to the beginning of a linked list. Your function takes two arguments - the head of the linked list and the value num to be added. Note that the list may be empty! Your function should modify the head of the linked list to point to the new node, and set the new node to point to the rest of the list (if not empty). Example: Initial Array: 4->2->3, key = 5...

  • Please fill in this code to reverse a linked list: (written in C/C++) #include #include #include...

    Please fill in this code to reverse a linked list: (written in C/C++) #include #include #include using namespace std; /* Link list node */ struct Node { int data; // your code here }; /* Function to reverse the linked list */ static void reverse(struct Node** head_ref) { // your code here } /* Function to push a node */ void push(struct Node** head_ref, int new_data) { // your code here } /* Function to print linked list */ void...

  • C++ Linux Question : Remove Nth Node from end of list Given a linked list, remove...

    C++ Linux Question : Remove Nth Node from end of list Given a linked list, remove the n-th node from the end of list and return its head. Example: Given linked list: 1->2->3->4->5, and n = 2. After removing the second node from the end, the linked list becomes 1->2->3->5. Note: Given n will always be valid. (i.e. n is greater than 0) Follow up: Could you do this in one pass? Hint: Maintain two pointers and update one with...

  • This is a code for linked list, it is about adding a node in the middle...

    This is a code for linked list, it is about adding a node in the middle of a list, I am really confused why int i = 2? can't it be 0? Add to the Middle • Allocate memory and store data for new node Traverse to node just before the required position of new node Change next pointers to include new node in between struct node *newNode; newNode = malloc(sizeof(struct node)); newNode->data = 4; struct node *temp head; for(int...

  • iImplement a Singly Linked List detectLoop in Java, it would check whether the linked list contains...

    iImplement a Singly Linked List detectLoop in Java, it would check whether the linked list contains a loop. Print true if yes, false if not. Test by using the following code: LL<Integer> L = new LL<>(); for (int i = 1000; i > 0; i-=3) sl.add(i); try { L.insert(122, L.getNode(70), L.getNode(21)); if (L.detectLoop()) System.out.println("True"); else System.out.println("False."); } catch(Exception e){ e.printStackTrace(); } class Linkedlist<E>{ private static class Node<E>{ private E element; private Node<E> next; public Node(E e, Node<E> n){ element =...

  • Im making a generic linked list. I cant figure out how to make an object of...

    Im making a generic linked list. I cant figure out how to make an object of my class from main. My 3 files are main.cpp dan.h dan.cpp The error is: 15 6 [Error] prototype for 'void ll<T>::insert()' does not match any in class 'll<T>' #include <iostream> #include <string> #include "dan.h" using namespace std; int main() { ll<int> work; work.insert(55);//THIS IS THE LINE THATS GIVING ME THE ERROR, Without this line it compiles and //runs. } #ifndef DAN_H #define DAN_H #include...

  • C programming A linked list is a linear data structure that allows us to add and remove items fro...

    c programming A linked list is a linear data structure that allows us to add and remove items from the list very quickly, by simply changing a few pointers. There are many different variations of linked lists. We have studied the doubly-linked, circular, with a dummy-header-node version of a linked list. In the class notes we studied several functions to manipulate a Linked List. For this assignment you must write the code for the following additional linked list functions: addFirst,...

  • Using C, I need help debugging this program. I have a few error messages that I'm...

    Using C, I need help debugging this program. I have a few error messages that I'm not sure how to fix. Here is the code I have: /* * C Program to Print a Linked List in Reverse Order */ #include <stdio.h> #include <stdlib.h> struct node { int num; struct node *next; }; int main() { struct node *p = NULL; struct node_occur *head = NULL; int n; printf("Enter data into the list\n"); create(&p); printf("Displaying the nodes in the list:\n");...

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
ADVERTISEMENT