gpt4 book ai didi

c++ - 如何删除添加到 C++ 链表中的最后一个元素

转载 作者:太空宇宙 更新时间:2023-11-04 13:44:05 29 4
gpt4 key购买 nike

我是第一次使用指针。我有一个程序可以将数字插入链表、打印列表并从列表中删除特定数字。它有效,除非我尝试删除最后插入的号码。

节点.h

#ifndef Node_h
#define Node_h

#include <iostream>
using namespace std;

class Node
{
public:
int data;
Node *next;

public:
Node();
};

#endif

节点.cpp

#include "Node.h"

Node::Node()
{
}

链表.h

#ifndef LinkedList_h
#define LinkedList_h

#include "Node.h"

class LinkedList
{
private:
Node *pL;

public:
LinkedList();
void insert(int nr1);
void deleteNr(int nr1);
void printL();
};

#endif

链表.cpp //这个程序正在创建一个数字的“链表”

#include "LinkedList.h"

LinkedList::LinkedList()
{
pL = NULL;
}

void LinkedList::insert(int nr1)
{
Node *p = new Node;
p->data = nr1;
p->next = pL;
pL = p;
}

void LinkedList::deleteNr(int nr1)
{
Node *p = pL;
Node *p2 = pL;
while (p != NULL & p->data != nr1)
{
p2 = p;
p = p->next;
}

if (p != NULL)
{
p2->next = p->next;
delete p;
}
}

void LinkedList::printL()
{
Node *p = pL;

while (p != NULL)
{
cout << p->data << "-> ";
p = p->next;
}
}

主要.cpp

#include "LinkedList.h"

int menu();

//////// main /////////
int main()
{
int choice1, nr1;
LinkedList lk1;

choice1 = menu();

while (choice1 <= 3)
{
if (choice1 == 1)
{
cout << "Enter number." << endl;
cin >> nr1;
lk1.insert(nr1);
}

else if (choice1 == 2)
{
cout << "Enter number." << endl;
cin >> nr1;
lk1.deleteNr(nr1);
}

else if (choice1 == 3)
{
lk1.printL();
cout << endl << endl;
}

else if (choice1 == 4)
{
cout << "Exit the program." << endl;
system("pause");
exit(1);
}

choice1 = menu();
} // end while loop
}

int menu()
{
int choice1;

cout << "1. Insert a number into the linked-list." << endl;
cout << "2. Delete a number from the linked-list." << endl;
cout << "3. Print the linked-list." << endl;
cout << "4. Exit the program." << endl;
cout << "Enter choice." << endl;
cin >> choice1;

return choice1;
}

最佳答案

你的问题是,通常情况下,p2 是列表中 p 后面的一个节点,但如果要删除第一个节点,则删除函数中的第一个 while 循环有 0 次迭代,p2 和 p 相同。头部被删除,但 pL 没有更新。它只是指向未分配的内存。这可能使它看起来像节点没有被删除,或者它可能导致段错误和崩溃。无论哪种方式,这都是错误的行为。您需要确保检查要删除的节点是第一个节点的情况并更新 pL。

尝试这样的事情

void LinkedList::deleteNr(int nr1)
{
Node *p = pL;
Node *p2 = pL;
if(p != NULL && nr1 == p->data)
{
pL = p->next;
delete p;
return;
}

while (p != NULL && p->data != nr1)
{
p2 = p;
p = p->next;
}

if (p != NULL)
{
p2->next = p->next;
delete p;
}
}

如果您希望能够删除链表中nr1所有 个实例,您需要添加另一个循环:

void LinkedList::deleteNr(int nr1)
{
Node *p = pL;
while(p != NULL && nr1 == p->data)
{
pL = p->next;
delete p;
p = pL;
}
Node *p2 = pL;

while (p != NULL)
{
p2 = p;
p = p->next;
if(nr1 == p->data)
{
p2->next = p->next;
delete p;
}
}
}

关于c++ - 如何删除添加到 C++ 链表中的最后一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26615287/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com