我的代码假设使用节点数组创建单链表。
每个节点都有可变项,其中包含数据和变量,其中包含列表中下一个节点的索引。最后一个节点在其下一个数据字段中具有-1以模拟nullptr。 head保存列表中第一个节点的索引。
由于某些原因,当我尝试创建新内存时,程序会抛出bad_alloc
的实例在抛出' std :: bad_alloc'的实例后终止调用 what():std :: bad_alloc
#include "ArrayList.h"
#include <iostream>
using namespace std;
ArrayList::ArrayList(char ch){
array = new Node[Size];
(array[0]).item = ch;
(array[0]).next = 1;
free = 1;
head = 0;
}
bool ArrayList::cons(char ch) {
if (this->isFull()){
this->doubleArray();
}
(array[free]).item = ch;
(array[free]).next = head;
head = free;
free++;
// cout << free << endl;
return true;
}
bool ArrayList::isFull() const{
int current = head;
int count =0;
while( (array[current]).next != -1 ){
count++;
current = (array[current]).next;
}
return (count == Size) ? true : false;
}
bool ArrayList::doubleArray() {
int oldSize = Size;
Size *=2;
Node* newArray = new Node[Size]; // problem occurs here, i think
int count =0;
while(oldSize >= count ){
(newArray[count]).item = (array[count]).item;
(newArray[count]).next = (array[count]).next;
count++;
}
free = count +1;
delete [] array;
array = newArray;
cout <<"free: "<< free << endl;
return true; // come up with thiss
}
void ArrayList::print() const{
if (head == -1) return;
int current = head;
cout << "[ ";
while( (array[current]).next != -1){
cout << (array[current]).item <<" ";
current = (array[current]).next;
}
cout << (array[current]).item <<"]";
return;
}
///////////////////////////////////
#ifndef ARRAYLIST_H
#define ARRAYLIST_H
#include <iostream>
using namespace std;
class Node{
public:
char item;
int next;
Node(){
next = -1;
}
Node(char input){
this->item = input;
next = -1;
}
};
class ArrayList{
public:
ArrayList(char ch);
int length() const;
void print() const;
private:
bool doubleArray();
bool isFull() const;
Node* array;
int Size = 5;
int head = -1;
int free = 0;
};
#endif
////////////////////////////////////////
#include <iostream>
#include "ArrayList.h"
using namespace std;
int main(){
ArrayList list('1');
list.cons('2');
list.cons('3');
list.cons('4');
list.cons('5');
list.cons('6');
list.cons('7');
list.print();
//cout << list.length();
return 0;
}