gpt4 book ai didi

c++ - 代码不编译 - 链表,按升序排序列表

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:02:33 26 4
gpt4 key购买 nike

我写了一个代码来获取一个带有数字的链表,并试图使该列表成为升序序列。不幸的是代码不符合,我不知道为什么。

我尝试过使用指针和引用,但我无法确定哪里出了问题。

#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() 应该返回指向节点的指针,因此返回 first 而不是 *first 并将返回类型更改为 列表节点*。然后将 print(sort(a)) 更改为 print(*sort(a))。看到它在这里运行:http://coliru.stacked-crooked.com/a/c3e72983e83f6914

关于c++ - 代码不编译 - 链表,按升序排序列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56957544/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com