c++ - 无法尝试删除不在 C++ 链接列表中的项目

标签 c++ singly-linked-list

在一个简单的 LinkedList 类中,我试图删除一个对象,当该项目存在时它工作正常但是当我尝试删除一个不存在的项目时,我的程序终止并说它刚刚停止工作...下面发布的是代码。有什么建议吗?

#include<iostream>
using namespace std;
class Node{
public:
    int data;
    Node* next;
    Node(){
        data=-1;
        next=NULL;
    }
    Node(int d){
        data=d;
        next=NULL;
    }
    Node(int d, Node* n){
        data=d;
        next=n;
    }
};
class LinkedList{
    public:
    Node* head;
    Node* dummy = new Node();
    LinkedList(){
        head=dummy;
    }
    LinkedList(Node* n){
        head=dummy;
        dummy->next=n;
    }
    void ins(Node* n){
        Node* current = head;
        while(current->next!=NULL&&current->next->data<=n->data){
            current=current->next;
        }
        n->next=current->next;
        current->next=n;
    }
    void print(){
        Node* current = head;
        while(current->next!=NULL){
            cout<<current->next->data<<endl;
            current=current->next;
        }
    }
    int peek(){
        if(head->next==NULL){
            cout<<"List is Empty"<<endl;
        }
        return head->next->data;
    }
    void rem(int toRemove){
        Node* current = head;
        while(current->next!=NULL&&current->next->data!=toRemove){
            current=current->next;
        }
        if(current->next->data==toRemove){
            current->next=current->next->next;
            cout<<"Removing Item"<<endl;
            return;
        }
        if(current->next->data!=toRemove){
            cout<<"No Item Found"<<endl;
            return;
        }
        if(current->next==NULL){
            cout<<"Not Removable since not there"<<endl;
            return;
        }
    }
};
int main(){
LinkedList* a = new LinkedList();
Node* n = new Node(5);
Node* nn = new Node(10);
Node* nnn = new Node(15);
Node* nnnn = new Node(12);
Node* nnnnn = new Node(7);
a->ins(n);
a->ins(nn);
a->ins(nnn);
a->ins(nnnn);
a->ins(nnnnn);
a->print();
a->rem(5);
a->print();
a->rem(13);
a->print();
return 0;
}

感谢任何帮助。谢谢,

最佳答案

在您的 rem() 函数中,您的 while 循环将您安全地带到一个非空的节点,但在 while 循环之后您不检查 current->next 是否不为空。如果它为 null,则在取消引用 current->next->data 时会崩溃。这就是我运行您的代码时发生的情况。

我建议循环直到找到要删除的那个,而不是在找不到时循环——你可能永远找不到它。

关于c++ - 无法尝试删除不在 C++ 链接列表中的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27471899/

相关文章:

c - 链接列表不适用于插入

java - 这张图有错误吗?

c - 为什么这段用于反向打印单向链表的代码段没有按预期工作?

c++ - 构建过程中的 QT 和 SQLITE 问题

python - 通过C++ 20协程制作python生成器

c++ - 我如何将此 int 数组的一部分复制到 C++ 中的另一个?

c - 从队列中使用 dequeue 方法时抛出异常

c++ - 降低程序的复杂度

c++ - QTcpSocket - 检查是否已连接

c - 如何将单链表改为双向链表?