Question

c++ modify the attached unsorted linked list class into a sorted linked list class #include <iostream>...

c++
modify the attached unsorted linked list class into a sorted linked list class

#include <iostream>
using namespace std;

template<class T>
struct Node {
    T data;//data field
    Node * next;//link field

    Node(T data) {
      this->data = data;
    }
};

template<class T>
class linked_list{
private:
      Node<T> *head,*current;
public:
      linked_list(){//constructor, empty linked list
        head = NULL;
        current = NULL;
      }

      ~linked_list(){
        current = head;
        while(current != NULL) {
          head = current->next;
          delete current;
          current = head;
        };

      }

      linked_list& add_node(int n) {//add a node at the end of the list

          if(head == NULL) {//empty list
            head = new Node<T>(n);
            head->next = NULL;
            current = head;
          } else {//non-empty list
            current->next = new Node<T>(n);
            current = current->next;
            current->next = NULL;
          }

          return *this;
      }

      void display(){
        //Node * tmp;
        current = head;
        while(current != NULL) {
          cout << current->data << endl;
          current = current->next;
        };
      }
};



int main() {

std::cout << "Hello World!\n";

linked_list<char> a;
a.add_node('a').add_node('c').add_node('b');
a.display();


return 0;
}

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

The sorting technique which i am going to use to sort the values of linked list is bubble sort . In sort() function , i have initialized two pointers namely start and end to point to head and NULL respectively . If the linked list is empty then it returns nothing. I have used a do-while loop until the end pointer points to the head node . In while loop the start pointer gets traversed upto the end pointer and compares the adjacent values . If the adjacent values are not in increasing order , then the values gets swapped using swap() function .

Note : in swap() function , the values gets swapped but not the pointers . we are not disturbing the pointers in the swap() function .

I have used a swapped variable so that after the values have been successfully sorted then the do-while loop should terminate . Please see my comments for better understanding .

CODE :

#include <iostream>
using namespace std;

template<class T>
struct Node {
T data;//data field
Node * next;//link field

Node(T data) {
this->data = data;
}
};

template<class T>
class linked_list{
private:
Node<T> *head,*current;
public:
linked_list(){//constructor, empty linked list
head = NULL;
current = NULL;
}

~linked_list(){
current = head;
while(current != NULL) {
head = current->next;
delete current;
current = head;
};

}

linked_list& add_node(int n) {//add a node at the end of the list

if(head == NULL) {//empty list
head = new Node<T>(n);
head->next = NULL;
current = head;
} else {//non-empty list
current->next = new Node<T>(n);
current = current->next;
current->next = NULL;
}

return *this;
}

void display(){
//Node * tmp;
current = head;
while(current != NULL) {
cout << current->data << endl;
current = current->next;
};
}
  

// BUBBLE SORT TECHNIQUE
void sort() // for sorting the values in a linked list
{
int swapped; // if all the values are in sorted order , then swapped is used to terminate the loop  
struct Node<T> *start=head;   
struct Node<T> *end = NULL;
  
/* Checking for empty list */
if (head == NULL)
return;
  
do
{
swapped = 0;
start = head;
  
while (start->next != end) // traversing the start pointer upto the end pointer
{
if (start->data > start->next->data) // comparing the adjacent values (bubble sort )
{
swap(start, start->next); // swapping the values if they are not sorted
swapped = 1; // inorder to run the loop again
}
start = start->next;
}
end = start; // traversing the end pointer in the reverse direction
}
while (swapped);
}

// for swapping the values of a and b
void swap(struct Node<T> *a, struct Node<T> *b)
{
T temp = a->data;
a->data = b->data;
b->data = temp;
}

};

int main() {

std::cout << "Hello World!\n";

linked_list<char> a;
a.add_node('a').add_node('c').add_node('b');
a.display();
a.sort();
cout<<"after sorting \n " ;
a.display();


return 0;
}

Add a comment
Answer #2

I only modified insertion method of above code. The idea is while inserting new node, we traverse through entire linked list and find first node which has greater data value than new node. Then we insert the new node before that node. Below is the code of entire program.

#include <iostream>
using namespace std;
template<class T>
struct Node {
T data;//data field
Node * next;//link field

Node(T data) {
this->data = data;
}
};
template<class T>
class linked_list{
private:
Node<T> *head,*current;
public:
linked_list(){//constructor, empty linked list
head = NULL;
current = NULL;
}

~linked_list(){
current = head;
while(current != NULL) {
head = current->next;
delete current;
current = head;
};

}

linked_list& add_node(int n)
{//add a node at the end of the list
  
if(head == NULL) {//empty list
head = new Node<T>(n);
head->next = NULL;
current = head;
}
else
{ //non-empty list
Node<T> *prev = NULL; // pointer to point previous node
current = head; // initalized with head
while (current!=NULL && current->data < n) // we traverse until n is greater
{
prev = current; // previous node
current = current->next; // moving to next node
}
if (prev==NULL) // if newly created should come first in list
{
head = new Node<T>(n); // making head as newly created list
head->next = current; // making head next as old head
  
}
else
{ // we are at a node with greater data value than n
prev->next = new Node<T>(n); // so we put new node in between previous and current nodes
prev->next->next = current; // new node next will be current
}
}
return *this;
}

void display(){
//Node * tmp;
current = head;
while(current != NULL) {
cout << current->data << endl;
current = current->next;
};
}
};

int main() {

std::cout << "Hello World!\n";

linked_list<char> a;
a.add_node('b').add_node('d').add_node('c').add_node('a').add_node('f');
a.display();


return 0;
}

add node method screenshot:

Sample output:

Add a comment
Know the answer?
Add Answer to:
c++ modify the attached unsorted linked list class into a sorted linked list class #include <iostream>...
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
  • C++ 1. Please use attached script for your reference to create the node structure and a...

    C++ 1. Please use attached script for your reference to create the node structure and a linked list class, say LinkedList, that has the following basic member methods:     constructor, destructor//IMPORTANT, display(), add_node(). 2. Please implement the following additional member methods:     Please feel free to change T with any data type you'd like to use for your node stricture's data type. -- addFirst(T data) // Adds an node with data at the beginning of the list -- pop() //...

  • 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...

  • Q) Modify the class Linked List below to make it a Doubly Linked List. Name your...

    Q) Modify the class Linked List below to make it a Doubly Linked List. Name your class DoublyLinkedList. Add a method addEnd to add an integer at the end of the list and a method displayInReverse to print the list backwards. void addEnd(int x): create this method to add x to the end of the list. void displayInReverse(): create this method to display the list elements from the last item to the first one. Create a main() function to test...

  • In C++, for the provided template linked list class create a derived class of it which...

    In C++, for the provided template linked list class create a derived class of it which adds the functionality to it to find the high and low value of any given data stored in the list. The derived class must be a template. LinkedList.h #pragma once #include <iostream> using namespace std; template <class T> class ListNode {    public:        T data;        ListNode<T>* next;        ListNode(T data)        {            this->data = data;...

  • 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++ 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...

  • #include <iostream> using namespace std; struct ListNode { float value; ListNode *next; }; ...

    #include <iostream> using namespace std; struct ListNode { float value; ListNode *next; }; ListNode *head; class LinkedList { public: int insertNode(float num); void deleteNode(float num); void destroyList(); void displayList(); LinkedList(void) {head = NULL;} ~LinkedList(void) {destroyList();} }; int LinkedList::insertNode(float num) { struct ListNode *newNode, *nodePtr = head, *prevNodePtr = NULL; newNode = new ListNode; if(newNode == NULL) { cout << "Error allocating memory for new list member!\n"; return 1; } newNode->value = num; newNode->next = NULL; if(head==NULL) { cout << "List...

  • ***CODE MUST BE IN C++*** Using the linked list in "basic linked list" which has a...

    ***CODE MUST BE IN C++*** Using the linked list in "basic linked list" which has a STRUCTURE for each node, write FUNCTION which starts at the head and outputs the value for each node until the last node is reached. Note: your function should work with the structure that is in this program. Please do not use the example which is for a class, but this example canbe helkpful.  Also note that the function must work no matter how many nodes...

  • Please rewrite this function using recursive function #include using namespace std; struct Node { char ch;...

    Please rewrite this function using recursive function #include using namespace std; struct Node { char ch; Node* next; }; class LinkedList { Node* head; public: LinkedList(); ~LinkedList(); void add(char ch); bool find(char ch); bool del(char ch); friend std::ostream& operator<<(std::ostream& out, LinkedList& list); }; LinkedList::LinkedList() { head = NULL; } LinkedList::~LinkedList() { Node* cur = head, * tmp; while (cur != NULL) { tmp = cur->next; delete cur; cur = tmp; } } void LinkedList::add(char ch) { Node* cur = head,...

  • BELOW IS THE CODE I ALREADY HAVE Linked List - Delete Modify Lab 5 and include...

    BELOW IS THE CODE I ALREADY HAVE Linked List - Delete Modify Lab 5 and include the method to delete a node from the Linked List. In summary: 1) Add the method Delete 2) Method call to delete, with a number that IS in the list 3) Method call to delete, with a number that is NOT in the list - Be sure to include comments - Use meaningful identifier names (constants where appropriate) import java.io.*; 1/ Java program to...

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