简体   繁体   中英

I want to sort a singly linked list in a descending order , I made a function but it doesn't seem to be working

This is my whole code I made a function to add to head and a function to print the whole list and a function to sort the list in a descending order. There is no error whenever I run the code and the linked lists doesn't rearrange in a descending order it prints out the same order

#include <iostream>
using namespace std;
#include <string.h>

class Node{
public:
    string data;
    Node* next , *head; 
    int counter=0;
};
class tsortedList :public Node{
public:

void printlist(){
    Node *t = head; 
    while (t != NULL){
            cout<<t->data<<", ";
            t = t->next;
        }   
}
void insert_at_beginning(string data){
            Node *temp = new Node();
            temp->data = data;
            temp->next = head;
            head = temp;
            counter++;
        }       
void Sort(){
        Node* temp;
        temp = head ; 
        string info ;
        for (int j = 0; j < counter; j++)
        {

            while ((temp->data) < (temp->next->data)  ) 
            {


                info=temp->data;
                temp->data = temp->next->data; 
                temp->next->data=info;
                temp = temp->next ; 
            }

            temp = temp->next ; 

        }
        temp = head ;
    }        
};
int main(){
    tsortedList obj;
    obj.insert_at_beginning("Apple");
    obj.insert_at_beginning("bannana");
    obj.insert_at_beginning("Zebra");
    obj.insert_at_beginning("Horse");
    obj.printlist();
    obj.Sort();
    obj.printlist();

}

I cannot understand your sort function. It is simply semantically wrong.

You could use the most simple bubble-sort algorithm and it will work.

For example like this (there are many more possible solutions):

    void Sort() {

        Node* temp1 = head;
        for (int i = 0; i < counter - 1; ++i) {
            Node* temp2 = temp1;
            for (int j = 0; j < counter - i ; ++j) {
                if (temp1->data > temp2->data) {
                    std::string s = temp1->data;
                    temp1->data = temp2->data;
                    temp2->data = s;
                }
                temp2 = temp2->next;
            }
            temp1 = temp1->next;
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM