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");...
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! 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...
Tower of Hanoi problem complete the problems please use this code #pragma once #include <iostream> #include...
Tower of Hanoi problem complete the problems please use this code #pragma once #include <iostream> #include <stack> #include <string> #include <vector> using namespace std; class TowersOfHanoi { friend ostream& operator<<(ostream& sink, const TowersOfHanoi& towers); public: //constructor TowersOfHanoi(); //custom methods unsigned move(unsigned new_n_disks = 6, ostream& new_sink = cout); private: //custom methods void move_aux(ostream& sink, unsigned n_disks, unsigned srce, unsigned dest, unsigned aux); //temporary variable unsigned _n_moves; //data const unsigned _n_towers; stack<unsigned>* _tower; }; #include "TowersOfHanoi.h" // ostream& operator<<(ostream& sink, const...
Please use the code I provided!! Use either bubble sort or selection sort!! Thank you in...
Please use the code I provided!! Use either bubble sort or selection sort!! Thank you in advance This lab involves adding a sorting function to an existing C++ template. In this module, a file is provided for you -- SortableBag.h -- that implements a simple "bag" (unsorted collection of numbers) structure with array storage. Part 1 Add a sort() method to this template, which should not return any values or take any arguments ('void' for both the return type and...
Add Bubble Sorting & Binary Search Functions to the following code (C++) #include<iostream> #include<fstream> #include<string> #include<iomanip>...
Add Bubble Sorting & Binary Search Functions to the following code (C++) #include<iostream> #include<fstream> #include<string> #include<iomanip> #include<algorithm> using namespace std; const int row = 10; const int col = 7;   ifstream name; ifstream grade; ofstream out; void readData(string stname[row], int stgrade[row][col]); void stsum(int stgrade[row][col], int total[row]); void staverage(int total[row], double average[row]); void stlettergrade(double average[row],char ltrgrade[row]); void displayData(string stname[row], int stgrade[row][col], int total[row], double staverage[row], char ltrgrade[row]); void swapltrgrade(char* xp, char* yp); int main() {    int STG[row][col] = { {0},{0}...
(Write a C# program DO NOT USE CLASS)Implement the merge sort algorithm using a linked list...
(Write a C# program DO NOT USE CLASS)Implement the merge sort algorithm using a linked list instead of arrays. You can use any kind of a linked structure, such as single, double, circular lists, stacks and/or queues. You can populate your list from an explicitly defined array in your program. HINT: You will not be using low, middle and high anymore. For finding the middle point, traverse through the linked list while keeping count of the number of nodes. Break...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT