C ++中链接列表的运行时错误

时间:2017-05-31 01:21:36

标签: c++ data-structures linked-list

每当我运行此代码以实现链接列表时,我都会收到运行时错误。我认为错误是在默认构造函数中,因为我试图运行只创建了对象的程序,没有其他操作完成。

linkedlist.h文件是

#ifndef LinkedList_h
#define LinkedList_h

#include<iostream>
#include<string>

using namespace std;

struct node{
    string song;
    node *next;
};

class LinkedList{
    private:
        node *head;
        int listLength;
    public:
        LinkedList();
        bool insertNode(node *newnode, int position);
        bool removenode(int position);
        void printList();
        ~LinkedList();
};

#endif

linkedlist.cpp文件是

#include "linkedlist.h"
#include<iostream>

LinkedList::LinkedList(){
    head = new node;
    head->song ="head";
    head->next=NULL;
    listLength = 0;
}

bool LinkedList::insertNode(node *newnode, int position){
    if(position<=0 || position >listLength+1)
        {
            cout<<"Error: position is out of range";
            return false;
        }
    if(head->next == NULL){
        head->next = newnode;
        listLength++;
        return true;
    }
    int count = 0;
    node *p=head;
    node *q=head;
    while(q){
        if(position == count){
            p->next=newnode;
            newnode->next = q;
            listLength++;
            return true;
        }
    p=q;
    q=p->next;
    count++;
    }
    cout<<"Unable to insert the element due to technical issues";
    return false;
}

bool LinkedList::removenode(int position){
    if(position<=0 || position > listLength+1){
        cout<<"Invallid position\n";
        return false;
    }
    if(head->next ==NULL){
        cout<<"The list is already empty\n";
        return false;
    }
    int count =0;
    node *q = head;
    node *p = head;
    while(q){
        if(count==position){
        p->next = q->next;
        delete q;
        listLength--;
        return true;
        }
    p=q;
    q=p->next;
    count++;
    }
    cout<<"Error removing elements";
    return false;
}

void LinkedList::printList(){
    int count=0;
    node *p = head;
    node *q = head;

    if(head->next==NULL){
        cout<<"The list is empty\n";
    }
    while(count<listLength){
        cout<<"\n"<<p->song<<endl;
        q=p;
        p=q->next;
        count++;
    }
}

LinkedList::~LinkedList() 
{
    node * p = head;
    node * q = head;
    while (q)
    {
        p = q;
        q = p -> next;
        if (q) delete p;
    }
    delete head;
}

main.cpp是

#include "linkedlist.h"
#include "linkedlist.cpp"
#include<iostream>

using namespace std;

int main(){
    node *A = new node;
    A->song = "Swatch";

    node *B = new node;
    B->song = "one plus 2";

    node *C = new node;
    C->song = "Woodland";

    LinkedList l;
    l.insertNode(A,1);
    l.insertNode(B,2);
    return 0;
}

1 个答案:

答案 0 :(得分:0)

看起来你永远不会在构造函数中初始化head。这将导致运行时错误。您需要添加类似

的语句
head = new node;

然后记得在你不再需要它时删除它。