c++ - 代码不编译 - 链表,按升序排序列表
问题描述
我编写了一个获取带有数字的链表的代码,并尝试将列表设为升序系列。不幸的是,代码没有被遵守,我不知道为什么。
我曾尝试使用指针和引用,但我无法解决问题所在。
#include <iostream>
using namespace std;
class ListNode {
public:
ListNode(const int &info) : data(info), nextPtr(0) {}
int getData() const { return data; }
ListNode *getNext() const { return nextPtr; }
void setNext(ListNode *next) { nextPtr = next; }
private:
int data;
ListNode *nextPtr;
};
ListNode sort(ListNode &temp) {
ListNode *first = &temp;
ListNode *curr = first;
ListNode *next = curr->getNext();
ListNode *found = 0;
while (curr->getNext() != 0) {
if (curr->getData() > next->getData()) {
if (curr == first) {
first = next;
found = curr;
}
else {
curr->setNext(next->getNext());
found = next;
}
break;
}
curr = next;
next = next->getNext();
}
curr = first;
next = curr->getNext();
while (curr->getNext() != 0) {
if (curr->getData() <= found->getData() &&
found->getData() < next->getData()) {
curr->setNext(found);
found->setNext(next);
break;
}
curr = next;
next = next->getNext();
}
return *first;
}
void print(ListNode &temp) {
ListNode *curr = &temp;
while (curr != 0) {
cout << curr->getData() << " ";
curr = curr->getNext();
}
cout << endl;
}
int main1() {
ListNode a(2);
ListNode b(5);
ListNode c(8);
ListNode d(13);
ListNode e(18);
ListNode f(7);
ListNode g(21);
a.setNext(&b);
b.setNext(&c);
c.setNext(&d);
d.setNext(&e);
e.setNext(&f);
f.setNext(&g);
print(a);
print(sort(a));
return 0;
}
我检查了一百次,不知道为什么这段代码没有编译。
解决方案
sort()
应该返回一个指向节点的指针,所以 returnfirst
而不是*first
并将返回类型更改为ListNode*
. 然后更改print(sort(a))
为print(*sort(a))
. 看到它在这里运行:http: //coliru.stacked-crooked.com/a/c3e72983e83f6914
推荐阅读
- python - django 嵌套查询或连接两个表
- api - 如何使用 Office.js API 阅读选定邮件列表
- javascript - 我的表单提交不起作用是什么问题阻止它工作?
- c# - 无法在 SqlQuery 中选择特定列 - 实体框架代码优先
- android - 我的应用程序崩溃并给出错误通道已无法恢复,将被处理
- r - 按每组条件过滤 data.table
- c# - 机器人无法加入机器人模拟器中的会话
- javascript - 如何实现切换按钮链接?
- php - 使用 php 和 laravel 将数据库数据从一个循环传递到多个 div
- java - 我想遍历hashmap并在其中调用对象的方法