[英]Regarding std::list, if I want to sort in descending order can I simply call “mylist.sort(>)”?
[英]I want to sort a singly linked list in a descending order , I made a function but it doesn't seem to be working
這是我的全部代碼我做了一個 function 添加到頭部和一個 function 打印整個列表和一個 function 以降序排序列表。 每當我運行代碼並且鏈接列表沒有按降序重新排列時都沒有錯誤它打印出相同的順序
#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();
}
我無法理解您的排序 function。 這在語義上是錯誤的。
您可以使用最簡單的冒泡排序算法,它會起作用。
例如像這樣(有更多可能的解決方案):
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;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.