簡體   English   中英

需要幫助C ++中的雙向鏈表

[英]need help doubly linked list in C++

我正在用c ++創建一個雙向鏈表。 代碼看起來很好,但當我試圖在列表中添加第二個節點時程序崩潰。 insert()函數有問題,但不知道如何解決它。

#include <iostream>
using namespace std;

class Node{
    int info;
    Node* next, *back;
    friend class LinkedList;
};

class LinkedList{
private:
    Node* head;
public:
    LinkedList();
    void print();
    void find(int, Node**, bool *);
    void insert(int);
    void remove(int);
    void destroylist();
    void modify(int, int);
    bool checkifempty();

};

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

void LinkedList::print(){
    Node* tmp;
    tmp=head;
    while(tmp!=NULL){
        cout<<tmp->info<<endl;
        tmp=tmp->next;
    }
}


void LinkedList::find(int key, Node** loc, bool *found){
    *loc = head;
    bool more=true;
    while((*loc)!=NULL && (*loc)->info)){

        *loc=(*loc)->next;


    }
    if (*loc==NULL)
    {
        *found=false;
    }
    else if ((*loc)->info==key){

        *found = true;
    }

}



void LinkedList::insert(int key){

    Node *NewNode,*loc=NULL;
    bool found;

    find(key,&loc,&found);
    //Creating NewNode
    NewNode=new Node;
    NewNode->info=key;
    //if list is empty
    if (checkifempty())
    {
        NewNode->next=NULL;
        head=NewNode;
    }
    //otherwise
    else
    {
        NewNode->back=loc->back;
        NewNode->next=loc;
        loc->back->next=NewNode;
        loc->back=NewNode;
    }
    //Connecting pointers to complete insertion


}

void LinkedList::remove(int key){
    Node* loc; bool found;
    find(key,&loc,&found);
    loc->back->next=loc->next;
    loc->next->back=loc->back;
    delete loc;
}

void LinkedList::destroylist(){
    Node* tmp;
    while(head!=NULL){
        tmp=head;
        head=head->next;
        delete tmp;
    }
}

bool LinkedList::checkifempty(){
    return (head==NULL?true:false);
}


int main(){
    LinkedList mylist;
    mylist.insert(10);
    mylist.insert(15);
    mylist.insert(11);
    system("pause");
    return 0;
}

在insert函數中,檢查從find檢索的指針:

if (loc != NULL) {
  // insert pointer into non-empty list

find函數和從中檢索的指針實際上是問題所在,因為您不檢查它是否返回了有效指針。

暫無
暫無

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

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