我正在尝试创建一个程序来删除链表第N个位置的节点。根据输出,应该是:
乔治· 贝蒂 费利克斯· 蕾妮 乔治· 贝蒂 费利克斯· 乔治· 费利克斯· 费利克斯
在repl.it(我的提交网站)上运行时,它提示我遇到了细分错误。然而,当我可以坚持的代码块我的个人电脑,它运行没有错误,但是,它只是输出的第一行是George
,Betty
,Felix
,和Renee
而不删除并重新输出。
这是我的代码:
#include <iostream>
#include <string>
using namespace std;
class Node {
public:
string name;
Node* next;
};
Node* head;
class LinkedList {
public:
LinkedList();
~LinkedList();
void push(string);
void output();
void remove(int);
private:
Node *first;
};
void LinkedList::remove(int n)
{
struct Node* temp1 = head;
if(n == 1)
{
head = temp1 -> next;
delete(temp1);
return;
}
int i = 0;
for(i = 0; i < n - 2; i++)
{
temp1 = temp1 -> next;
}
struct Node* temp2 = temp1 -> next;
temp1 -> next = temp2 -> next;
delete(temp2);
}
LinkedList::LinkedList()
{
first = NULL;
}
LinkedList::~LinkedList()
{
Node *current=first;
while(current!=NULL)
{
Node *ptr=current;
current = current->next;
delete(ptr);
}
}
void LinkedList::push(string data)
{
Node *temp;
temp = new Node;
(*temp).name = data;
(*temp).next = first;
first = temp;
}
void LinkedList::output()
{
Node *current = first;
while(current!=NULL)
{
cout << (*current).name << endl;
current = (*current).next;
}
cout << endl;
}
int main() {
LinkedList students;
students.push("Renee");
students.push("Felix");
students.push("Betty");
students.push("George");
students.output();
students.remove(3);
students.output();
students.remove(1);
students.output();
students.remove(0);
students.output();
}
除了 LinkedList::remove
通过first
成员变量管理列表之外,所有代码都适用。但是LinkedList::remove
reference head
,一个可疑的未使用的全局变量。我有信心甚至根本不在代码中。
删除global head
,然后更改LinkedList::remove
为:
void LinkedList::remove(int n)
{
Node **pp = &first;
while (*pp && n-- > 1)
pp = &(*pp)->next;
if (*pp)
{
Node *tmp = *pp;
*pp = tmp->next;
delete tmp;
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句