【问题标题】:How to create a bubble sort for a doubly linked list with a swap function?如何为具有交换功能的双向链表创建冒泡排序?
【发布时间】:2015-10-18 21:42:30
【问题描述】:

我试图弄清楚如何为 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++){

}
}

我遇到的问题是交换函数,它只用那个参数交换列表中的节点。

【问题讨论】:

    标签: c++ sorting linked-list bubble-sort doubly-linked-list


    【解决方案1】:

    您需要做的就是调整两者的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;
    }
    

    【讨论】:

    • 您忘记在两个节点之间交换键值,但这也应该不是什么大问题。 int temp = this.key; this.key=that-&gt;key; that-&gt;key=temp;
    • @GeriPapi 没有必要:它是确定列表布局中位置的链接。当然,您可以采取相反的观点:只需交换密钥,不要打扰。这取决于列表节点的内存布局是否重要。
    • 如何将交换放入我的冒泡排序函数中? @user268396
    • 你应该创建一个static气泡成员函数。在您的循环中,您需要在列表的节点上以特定方向迭代并考虑列表边界。交换成员函数与数组的普通冒泡排序中的交换操作占据相同的位置,左侧或右侧操作数是调用 swap() 函数的 this 对象(左侧用于向前迭代,右侧用于向后迭代)。
    • 您可以在这里放一个代码示例吗?只是这仍然令人困惑。
    猜你喜欢
    • 1970-01-01
    • 2014-02-04
    • 2022-01-09
    • 2011-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多