gpt4 book ai didi

c++ - 在 C++ 中使用冒泡排序对链表进行排序

转载 作者:行者123 更新时间:2023-11-30 05:38:07 25 4
gpt4 key购买 nike

我一直在尝试使用交换函数对双向链表进行冒泡排序。我的问题是交换函数是否交换指针,而不仅仅是数据?我的代码告诉我它只交换数据而不交换指针。有什么方法可以有效地交换链表上的指针?请告诉我代码,因为我在编码方面非常缺乏经验,而且我不理解其他答案中的其他代码。

void sortPoly(PolyNode* a)
{
PolyNode* head =a;
PolyNode* current = head;
PolyNode* current_next = current->next;


int len =Polylength(current);

if(len ==1 || len ==0)
{
return;
}

for(int i =0; i < len; i++)
{
for (int j =0; j< len -i; j++)
{
int sum = current->expx + current->expy;
cout << "sum=" << sum << endl;
int next_sum = current_next->expx + current_next->expy;
cout << "\t nextsum=" << next_sum << endl;

if( sum < next_sum)
{
cout << "current=" << current->coef << "expx = " << current->expx << "expy=" << current->expy << endl;
cout << "current_next=" << current_next->coef << "expx = " << current_next->expx << "expy=" << current_next->expy << endl;

std:: swap(current, current_next);
cout << endl;
cout << "swapped" << endl;

cout << "current=" << current->coef << "expx = " << current->expx << "expy=" << current->expy << endl;
cout << "current_next=" << current_next->coef << "expx = " << current_next->expx << "expy=" << current_next->expy << endl;

cout << "current=" << current->coef << "expx = " << current->expx << "expy=" << current->expy << endl;
cout << "current_next=" << current_next->coef << "expx = " << current_next->expx << "expy=" << current_next->expy << endl;

current = current->next;

current_next = current->next->next;
cout << "current=" << current->coef << "expx = " << current->expx << "expy=" << current->expy << endl;
cout << "current_next=" << current_next->coef << "expx = " << current_next->expx << "expy=" << current_next->expy << endl;
}
}

}

这是我的结构:

    struct PolyNode
{
int coef;
int expx;
int expy;
PolyNode* prev;
PolyNode* next;
};

请在 Mac 终端上找到以下我的回复。 Result for input a = xy+5-2x^6+7x^4y^2+5x^2-y^2, b= y-x+5

最佳答案

我认为您可能在交换功能方面存在问题。我不认为 std::swap 也可以交换 prev 和 next 引用。可以肯定的是,您可以实现自己的交换。我会用这个函数来做到这一点。

void swap(PolyNode* node1, PolyNode* node2){
PolyNode* prev = node1->prev;
PolyNode* next = node2->next;
if (prev)
prev->next = node2;
if (next)
next->prev = node1;

node1->next = next;
node1->prev = node2;

node2->prev = prev;
node2->next = node1;
}

顺便说一句,您必须将迭代移出 if。

current = current->next;
current_next = current->next->next;

部分必须在 if

之外

关于c++ - 在 C++ 中使用冒泡排序对链表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32933774/

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