Question

In: Computer Science

Please use C++, linked list and Bubble Sort to slove this problem. #include <iostream> #include <time.h>...

Please use C++, linked list and Bubble Sort to slove this problem.

#include <iostream>
#include <time.h>

using namespace std;

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


class LinkedList {

private:
ListNode *head = nullptr;
public:

void addNode(int x)
{
ListNode *p = new ListNode(x);
if (head == nullptr)

head = p;

else
{
ListNode *q = head;
while (q->next != nullptr)
q = q->next;
q->next = p;
}
}

void display()
{

ListNode *p = head;
if (p != nullptr)
{
while (p->next != nullptr)
{
cout << p->data << " -> ";
p = p->next;

}
cout << p->data << " @" << endl;
}
}

void sortList()

{

Please finish this part

}


int main()
{


LinkedList ll;
ll.addNode(23);
ll.addNode(91);
ll.addNode(2);
ll.addNode(21);
ll.addNode(2);
ll.addNode(36);
ll.addNode(42);
ll.addNode(12);
ll.addNode(30);
ll.addNode(19);
ll.sortList(); /// Implement the function



ll.display();
ll.deleteAll();

return 0;

}

Solutions

Expert Solution

The required code is added below followed by the output. The explanation of the complex code is added with the comment lines as well.

CODE:


#include <iostream>
#include <time.h>

using namespace std;

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


class LinkedList {

    private:
        ListNode *head = nullptr;
    public:

    void addNode(int x)
    {
        ListNode *p = new ListNode(x);
        if (head == nullptr)
            head = p;
        else
        {
            ListNode *q = head;
            while (q->next != nullptr)
                q = q->next;
            q->next = p;
        }
    }

    void display()
    {
        ListNode *p = head;
        if (p != nullptr)
        {
            while (p->next != nullptr)
            {
                cout << p->data << " -> ";
                p = p->next;
            }
        cout << p->data << " @" << endl;
        }
    }

    void sortList()

    {
        ListNode *q = head;              // INITIALIZED THE TRAVERSING POINTER WITH HEAD
        int n = 1;                       // N TO COUNT THE NUMBER OF ELEMENTS
        while (q->next != nullptr){
                q = q->next;
                n++;                     // INCREMENT N FOR EACH NEW POINTER
            }

        ListNode** curr;                  // A POINTER TO A POINTER OF NODE, WHICH WILL HELP IN SWAPPING

        for(int i=0;i<n;i++){              // PASS LOOP AS BUBBLE SORT

            curr = &head;                 // INITIALIZE WITH ADDRESS OF HEAD

            for(int j=0;j<n-i-1;j++){      // ANOTHER LOOP WHICH PLACES THE MAX ELEMENT INTO N-I'TH NODE

                ListNode* node1 = *curr;   // TWO NODE POINTERS FOR CURR AND NEXT
                ListNode* node2 = node1->next;


                if (node1->data > node2->data){  // IF DATA OF NODE 1 IS GREATER THAN 2 THEN SWAP ELSE DO NOTHING

                    ListNode* temp = node2->next;
                    node2->next = node1;
                    node1->next = temp;
                    *curr = node2;

                }
                curr = &(*curr)->next;          // INITIALIZE THE CURR WITH ADDRESS OF NEXT NODE.

            }

        }


    }

    void deleteAll(){
        ListNode *curr = head;
        while (curr != nullptr){
                ListNode* next = curr->next;
                delete curr;
                curr = next;
            }
        head = nullptr;
    }
};


int main()
{


    LinkedList ll;
    ll.addNode(23);
    ll.addNode(91);
    ll.addNode(2);
    ll.addNode(21);
    ll.addNode(2);
    ll.addNode(36);
    ll.addNode(42);
    ll.addNode(12);
    ll.addNode(30);
    ll.addNode(19);
    ll.sortList(); /// Implement the function



    ll.display();
    ll.deleteAll();
    return 0;

}

OUTPUT:

2 -> 2 -> 12 -> 19 -> 21 -> 23 -> 30 -> 36 -> 42 -> 91 @

NOTE: In case of any query, mention it in the comment section. HAPPY LEARNING!!


Related Solutions

Please use C++ and linked list to solve this problem Linked list 1 -> 3 ->...
Please use C++ and linked list to solve this problem Linked list 1 -> 3 -> 4 -> 5-> 6 ->7 replaceNode( 5 , 6) // Replace 5 with 6     result 1 -> 3 -> 4 -> 6 -> 6 ->7 Base code #include <iostream> using namespace std; class Node { public:     int data;     Node *next;     Node(int da = 0, Node *p = NULL) {         this->data = da;         this->next = p;     } };...
Please use C++ and linked list to solve this problem Linked list 1 -> 2 ->...
Please use C++ and linked list to solve this problem Linked list 1 -> 2 -> 3 -> 4 -> 5-> 6 ->7 replaceNode( 5 , 6) // Replace 5 with 6     result 1 -> 2 -> 3 -> 4 -> 6 -> 6 ->7 Base code #include <iostream> using namespace std; class Node { public:     int data;     Node *next;     Node(int da = 0, Node *p = NULL) {         this->data = da;         this->next =...
Complete the C++ code #include <iostream> #include <stdlib.h> #include <time.h> using namespace std; struct Cell {...
Complete the C++ code #include <iostream> #include <stdlib.h> #include <time.h> using namespace std; struct Cell { int val; Cell *next; }; int main() { int MAX = 10; Cell *c = NULL; Cell *HEAD = NULL; srand (time(NULL)); for (int i=0; i<MAX; i++) { // Use dynamic memory allocation to create a new Cell then initialize the // cell value (val) to rand(). Set the next pointer to the HEAD and // then update HEAD. } print_cells(HEAD); }
I need to write a method that sorts a provided Linked list with bubble sort and...
I need to write a method that sorts a provided Linked list with bubble sort and using ONLY Java List Iterator Methods (Link Below) https://docs.oracle.com/javase/8/docs/api/java/util/ListIterator.html     public static <E extends Comparable<? super E>> void bubbleSort(List<E> c) throws Exception {     // first line to start you off     ListIterator<E> iit = c.listIterator(), jit;     /**** Test code: do not modify *****/     List cc = new LinkedList(c);     Collections.sort(c);     ListIterator it1 = c.listIterator(), it2 = cc.listIterator(); while (it1.hasNext()) { if (!it1.next().equals(it2.next()))         throw new Exception("List not sorted");...
Develop and pseudocode for the code below: #include <algorithm> #include <iostream> #include <time.h> #include "CSVparser.hpp" using...
Develop and pseudocode for the code below: #include <algorithm> #include <iostream> #include <time.h> #include "CSVparser.hpp" using namespace std; //============================================================================ // Global definitions visible to all methods and classes //============================================================================ // forward declarations double strToDouble(string str, char ch); // define a structure to hold bid information struct Bid { string bidId; // unique identifier string title; string fund; double amount; Bid() { amount = 0.0; } }; //============================================================================ // Static methods used for testing //============================================================================ /** * Display the bid information...
how do you write a bubble sort function in python that sorts a linked list and...
how do you write a bubble sort function in python that sorts a linked list and if any duplicate are placed bext ti each other?
Use C language , pointer limit use //#include <stdio.h> //#include <stdlib.h> //#include <time.h> For example, I...
Use C language , pointer limit use //#include <stdio.h> //#include <stdlib.h> //#include <time.h> For example, I have random array [4,2,7,1,9,8,0]. Sort the array's index but cannot change the position of item in the array, if you copy the array to a new array, you also cannot change the item's position in array. The index now is[0,1,2,3,4,5,6] The output should be[6,3,1,0,2,5,4]
IN C ++ PLEASE CODE FOR BUBBLE SORT---Add code to sort the bowlers. You have to...
IN C ++ PLEASE CODE FOR BUBBLE SORT---Add code to sort the bowlers. You have to sort their parallel data also. Print the sorted bowlers and all their info . You can use a bubble sort or a shell sort. Make sure to adjust your code depending on whether or not you put data starting in row zero or row one. Sort by Average across, lowest to highest.  The highest average should then be on the last row.. When you sort...
*In C++ Please! This problem uses the concept of linked list What is a C++ structure?...
*In C++ Please! This problem uses the concept of linked list What is a C++ structure? Store product-id, product-name, and price per unit in a C++ structure. Use a C++ class with a member variable of that structure and provide read and write member functions for the product details. Suppose the product names are stored in alphabetical order, Write the C++ insert function to insert a new product ‘tooth brush’ in that linked list. Suppose the product names are stored...
I need the following code completed: #include <iostream> #include <time.h> #include "CSVparser.hpp" using namespace std; //============================================================================...
I need the following code completed: #include <iostream> #include <time.h> #include "CSVparser.hpp" using namespace std; //============================================================================ // Global definitions visible to all methods and classes //============================================================================ // forward declarations double strToDouble(string str, char ch); // define a structure to hold bid information struct Bid { string bidId; // unique identifier string title; string fund; double amount; Bid() { amount = 0.0; } }; // FIXME (1): Internal structure for tree node struct Node {    Bid data; Node *left; Node...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT