我正在研究从链表中删除节点的迭代删除函数,我认为代码应该可以正常工作。但是当我不能使用"delete"来删除列表的第一个节点时。代码是:# include使用命名空间std;
struct Node
{
int data;
Node* next;
};
Node* GetNewNode(int data)
{
Node* newNode = new Node;
newNode->data = data;
newNode->next = NULL;
return newNode;
}
Node* Insert(Node *root, int data)
{
if (root == NULL)
{
root = GetNewNode(data);
}
else
root->next = Insert(root->next, data);
return root;
}
void Delete_k(Node *root, int k)
{
int i = 0;
Node* P = new Node;
if (k == 1)
{
P = root;
root = root->next;
delete P;
}
else
{
for (int i = 1; i <= k - 2; i++)
{
root = root->next;
}
root->next = root->next->next;
}
}
void Output(Node* root)
{
if (root == NULL)
{
root = root->next;
}
while (root != NULL)
{
cout << root->data << " ";
root = root->next;
}
}
int main()
{
int n, a, pos;
Node* root = NULL;
cout << "Input your list hear: ";
cin >> n;
while (n > 0)
{
root = Insert(root, n);
cin >> n;
}
Output(root);
cout << "nDelete Pos?: ";
cin >> pos;
Delete_k(root, pos);
Output(root);
}
我有这个问题
void Delete_k(Node *root, int k)
{
int i = 0;
Node* P = new Node;
if (k == 1)
{
P = root;
root = root->next;
delete P;
}
else
{
for (int i = 1; i <= k - 2; i++)
{
root = root->next;
}
root->next = root->next->next;
}
}
问题:
void Delete_k(Node *root, int k)
根节点的值是通过引用传递的,但是指向它的指针不是。
结果:Delete_k
的根是main
的根的副本。Delete_K的根被重指向并删除。Main的根现在指向垃圾内存。结束游戏程序。
解决方案:
提供对根指针的引用,这样它就不会被复制。
void Delete_k(Node *& root, int k)
或者从Delete_k返回root。
Node * Delete_k(Node * root, int k)
{
//existing code
return root;
}