簡體   English   中英

無法嘗試刪除不在C ++中的LInkedList中的項目

[英]Failure to try to remove item not in LInkedList in C++

在一個簡單的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循環將您安全地帶到不為null的節點,但是while循環之后,您無需檢查current-> next是否不為null。 如果為null,則在取消引用current-> next-> data時將崩潰。 這是我運行您的代碼時發生的情況。

我建議循環,直到您找到要刪除的循環為止,而不是在找不到時不循環-您可能永遠找不到。

在此循環之后:

   while(current->next!=NULL&&current->next->data!=toRemove){
        current=current->next;

您可以有兩種情況:

  • 您已找到數據:
  • current->next==NULL因為您設法到達列表的末尾

您執行的下一條語句是

    if(current->next->data==toRemove){

但是,如果current->nextNULL ,則嘗試取消引用空指針並獲取segfault! 您必須首先檢查您是否不為NULL。

編輯:更正此錯誤后,我相信您還必須考慮其他問題:

  • 如果要刪除第一個元素怎么辦? 你沒有預見到更新 head時發生這種情況。 無論如何,當您開始查看下一個數據時,您會錯過它。 抱歉,我沒有注意到虛擬節點;-)
  • 你的三個if似乎是相互排斥的,所以你應該將它們與連接else

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM