我在创建循环双向链表时遇到问题。添加新节点时,我的代码似乎工作正常。它在删除每个其他节点时也有效。当我尝试擦除2个连续节点时出现问题。在过去的两天里,我已经查看了我的代码,虽然我发现了一些错误但没有更正问题。
void LinkedList::insert(Node *newnode, Node * pred)
{
Node *after;
if ((empty()) && (pred != head))
{
cout << "*&$MU##\n";
}
else
{
after = pred->next;
newnode->next = pred->next;
newnode->pred = pred;
pred->next->pred = newnode;
pred->next = newnode;
listSize++;
}
}
void LinkedList::erase(Node *pred)
{
Node *actual; //actual node to be deleted
Node *after; //node after the node to be deleted
if (!empty())
{
actual = pred->next;
after = actual->next;
pred->next = after;
after->pred = pred;
actual->next = '\0';
actual->pred = '\0';
listSize--;
}
}
添加节点的命令如下:mylist.insert(newnode,pred) 擦除节点的命令是:erase(pred)
我相信当我擦除节点时会出现问题,因为我的函数将pred和next值设置为NULL。当我使用以下节点再次调用擦除功能时,它不能再执行以下actual = pred->next; after = actual->next;
,因为前一个命令已将该节点的pred和next设置为NULL。
任何帮助将不胜感激。
我已决定为我的LinkedList.cpp添加整个代码,以防出现问题。
#include "stdafx.h"
#include <iostream>
using namespace std;
#include "Node.h"
#include "LinkedList.h"
LinkedList::LinkedList()
{
Node * hnode = new Node('?');
head = hnode;
listSize = 0;
first = head;
first->next = first;
//first->pred = first;
}
bool LinkedList::empty()//O(1)
{
if (first->next == first)
return 1;
else
return 0;
}
void LinkedList::insert(Node *newnode, Node * pred)
{
Node *after;
if ((empty()) && (pred != head))
{
cout << "*&$MU##\n";
}
else
{
after = pred->next;
newnode->next = pred->next;
newnode->pred = pred;
pred->next->pred = newnode;
pred->next = newnode;
listSize++;
}
}
void LinkedList::erase(Node *pred)
{
Node *actual; //actual node to be deleted
Node *after; //node after the node to be deleted
if (!empty())
{
actual = pred->next;
after = actual->next;
pred->next = after;
after->pred = pred;
actual->next = '\0';
actual->pred = '\0';
listSize--;
}
}
void LinkedList::display()
{
Node * current_node;
current_node = first;
do
{
cout << current_node->data << " ";
current_node = current_node->next;
} while (current_node != first);
cout << listSize<< '\n';
}