如何使用交换函数为双向链表创建冒泡排序?

时间:2015-10-18 21:42:30

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

我试图找出如何为名为DNode *DNode::bubble()的DNode编写成员函数    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++){

}
}

我遇到问题的是交换功能,只用一个参数交换列表中的节点。

1 个答案:

答案 0 :(得分: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;
}