【发布时间】:2016-05-07 22:02:47
【问题描述】:
我正在实现一个从未排序的双向链表中删除重复项的函数。我删除了其他功能以使代码更简短、更清晰。请假设 InsertFront 等其他功能正常工作。
当我删除重复项时,我无法从我的 Node 类中附加 prev 指针。我不确定我是否正确附加了 prev 指针。我目前遇到段错误。谢谢。
这是我的头文件。 dlinkedlist.h
#ifndef _DLINKEDLIST_H_
#define _DLINKEDLIST_H_
#include <cstdlib>
#include <stdexcept>
#include <string>
#include <iostream>
using namespace std;
template <class T>
class Node
{
public:
T data;
//string data;
Node<T>* prev;
Node<T>* next;
// default constructor
Node(T value)
{
data = value;
prev = NULL;
next = NULL;
}
};
// DLinkedList class definition
template <class T>
class DLinkedList
{
private:
// DLinkedList private members
int size; // number of items stored in list
Node<T>* front; // references to the front
Node<T>* back; // and back of the list
DLinkedList();
DLinkedList(const DLinkedList& ll);
~DLinkedList();
void RemoveDuplicates();
}
这是我的实现 dlinkedlist.cpp
#ifdef _DLINKEDLIST_H_
#include <cstdlib>
#include <stdexcept>
#include "dlinkedlist.h"
#include <string>
#include <iostream>
using namespace std;
template <class T>
void DLinkedList<T>::RemoveDuplicates() {
Node<T> *current, *runner, *dup;
current = front;
cout << "Removing the duplicates..." << endl;
while (current != NULL && current->next != NULL) {
runner = current;
while (runner->next != NULL) {
if(current->data == runner->next->data) {
dup = runner->next;
runner->next = runner->next->next;
runner->next->prev = runner->next->prev->prev; //trying to connect to previous node. Works without this line.
delete dup;
}
else {
runner = runner->next;
}
}
current = current->next;
}
}
这是我的测试文件。测试.cpp
#include <cstdlib>
#include <iostream>
#include <string>
#include "ccqueue.h"
#include "dlinkedlist.h"
#include "ticket.h"
using namespace std;
void LLTest();
int main()
{
cout << "\nEntering DLinkedList test function..." << endl;
LLTest();
cout << "...DLinkedList test function complete!\n" << endl;
return 0;
}
void LLTest()
{
// default constructor, InsertFront, InsertBack, ElementAt
DLinkedList<int> lla;
lla.InsertFront(2);
cout << "-------------------------------------------------\n";
lla.InsertBack(5);
lla.InsertBack(10);
lla.InsertBack(2);
cout << "-------------------------------------------------\n";
lla.RemoveDuplicates();
}
感谢您的宝贵时间。
【问题讨论】:
-
我不知道为什么这会导致问题,但可能值得花一点时间看看将
runner->next->prev = runner->next->prev->prev;更改为runner->next->prev = runner;是否会有所作为 -
感谢您的回复。不幸的是,这不起作用并导致了段错误。
-
双向链表很棘手。最好定义一个通用函数,例如
removeNode(),对其进行调试,然后将其用作removeDuplicates()函数的一部分。
标签: c++ pointers linked-list