每當我運行此代碼以實現鏈接列表時,我都會遇到運行時錯誤。我認爲錯誤是在默認的構造函數中,因爲我試圖運行程序,其中只有對象沒有被創建。C++中的linkedlists運行時錯誤
的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;
}
請編輯您的問題以提供[mcve]。 –
「我收到一個運行時錯誤」。然後調試它。這就是人們在發生錯誤時所做的事情。最好的工具來幫助你,這是一個調試器。 – kaylum