C++ 我为c+中的字符链表设计了一个排序算法+;但它没有';行不通
我曾尝试为我的链表程序构建一个排序算法,通过检查第一个元素与第二个、第三个等元素,将链表按字母顺序排序,然后将第二个元素与其余元素进行比较等等,但它不起作用。怎么了C++ 我为c+中的字符链表设计了一个排序算法+;但它没有';行不通,c++,linked-list,C++,Linked List,我曾尝试为我的链表程序构建一个排序算法,通过检查第一个元素与第二个、第三个等元素,将链表按字母顺序排序,然后将第二个元素与其余元素进行比较等等,但它不起作用。怎么了 struct list* sort_list(struct list *head) { struct list *current= (struct list*)malloc(sizeof(struct list)); struct list *previous=(struct list*)malloc(
struct list* sort_list(struct list *head)
{
struct list *current= (struct list*)malloc(sizeof(struct list));
struct list *previous=(struct list*)malloc(sizeof(struct list));
struct list *point=(struct list*)malloc(sizeof(struct list));
char tmp[30];
current = head;
previous = NULL;
point=head;
while(point!=NULL)
{
while (current != NULL)
{
if(strcmp(point->data,current->data)>0)
{
swap(head,point,current);
}
previous = current;
current = current->next;
}
point=point->next;
}
return head;
}
void swap(struct list *head,struct list *first,struct list *second) {
char *tempValue;
tempValue = first->data;
first->data = second->data;
second->data = tempValue;
}
列表结构:
struct list
{
char *data;
struct list *next;
}list;
替换
while (point != NULL) {
while (current != NULL) {
借
将列出的所有代码替换为:
std::list<char> myList;
// fill my list with a bunch of characters
myList.sort();
你能提供列表结构的代码吗?这真的不是
C++
,这一事实的一些死赠品是原始指针、struct
乱七八糟、strcmp
和malloc
。在C++中,你将用<代码> STD::清单,<代码> STD::String 和swap
不使用第一个参数head
,传递它真的没有意义,是吗?std::sort
不适用于列表。你需要这个成员函数。哦。。。打字太快了。更正。有疑问。实际上,正如你在评论中提到的,我需要填写一些字符,例如,用于排序。我已经从一个文件(作业的一部分)中读到了列表中的单词。如何使用它?如果需要对单词进行排序,则可以将其更改为字符串列表:std::list myList;/*填写字符串*/myList.sort()代码>(注意:这将进行区分大小写的排序;如果需要区分大小写的排序,则需要编写一个比较函数并将其传递到排序方法调用中)
std::list<char> myList;
// fill my list with a bunch of characters
myList.sort();
std::string myList;
// fill my list with a bunch of characters
std::sort(myList.begin(), myList.end());