gpt4 book ai didi

c++ - 如何为具有交换功能的双向链表创建冒泡排序?

转载 作者:行者123 更新时间:2023-11-28 06:01:28 24 4
gpt4 key购买 nike

我想弄清楚如何为 DNode 编写一个名为 DNode *DNode::bubble() 的成员函数,用于 DNode *head 可以对链表进行冒泡排序并返回新的头部。 我想使用一个成员函数 void swap(DNode *that) 交换两个节点。

到目前为止,这是我对 .h 和 .cpp 文件的了解:

#ifndef DNODE_H
#define DNODE_H
class DNode {

public:

int key;
DNode *next;
DNode *prev;

void add(int key);
void print();
DNode();
DNode *bubble();
void swap(Dnode *that);
};

#endif

#include "DNode.h"
#include <cstdlib>
#include <iostream>
using namespace std;

void DNode::swap(DNode *that){
DNode *temp = this;
DNode *R1, *L1, *R2, *L2;

}

Dnode *Dnode::bubble(){
DNode *temp = this;
int count = 0;
while(start != NULL){
count++;
start = start->next;
}

for(int i = 0; i < count; i++){

}
}

我遇到的问题是仅使用一个参数交换列表中的节点的交换函数。

最佳答案

那么您需要做的就是调整两者的 nextprev 成员,并同步这些元素的上一个和下一个元素的链接:

void DNode::swap(DNode *that) 
{
// this->prev->next points back to 'this' should become 'that'
if(this->prev) {
this->prev->next = that;
}
// this->next->prev points back to 'this' should become 'that'
if(this->next) {
this->next->prev = that;
}
// that->prev->next points back to 'that' should become 'this'
if(that->prev) {
that->prev->next = this;
}
// that->next->prev points back to 'that' should become 'this'
if(that->next) {
that->next->prev = this;
}
// remember whatever 'this' ->next and ->prev point to
DNode * n1 = this->next, * p1 = this->prev;
// let 'this' take the position of 'that in the list
this->prev = that->prev;
this->next = that->next;
// let 'that' take the position of the original 'this' in the list.
that->prev = p1;
that->next = n1;
}

或者:如果您只是想交换列表中特定逻辑位置的,那么您也可以简单地交换值:

void swap(DNode* that)
{
int old = this->key;
this->key = that->key;
that->key = old;
}

关于c++ - 如何为具有交换功能的双向链表创建冒泡排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33203610/

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