我的教授给了我们这个LinkedList.h文件并说我们必须使用它而不是全部编辑它。我确信这是可能的,但我在实现insertFront函数时遇到了很多麻烦。
#ifndef LINKEDLIST_H_
#define LINKEDLIST_H_
/*
* A singularly linked list
*/
#include <string>
class LinkedList {
public:
// Default Constructor of the linked list
LinkedList();
// Deconstructor
~LinkedList();
// Removes the first element from the linked
// list and returns it
char removeFront();
// Add to the front of the linked list
void insertFront(char c);
// Returns the element stored at the front of the linked list
char front() const;
// Returns the number of elements returned
int count() const;
// Returns a string representation of the linked list
std::string toString();
private:
char data;
LinkedList* next;
};
#endif
这是我迄今为止使用LinkedList.cpp文件尝试过的。它正确编译但在尝试在我创建的新对象中分配任何变量时崩溃(在insertFront(char c)函数内部。
#include "LinkedList.h"
#include <string>
#include <iostream>
using namespace std;
LinkedList::LinkedList(){
next = NULL;
data = 'x';
}
char LinkedList::removeFront(){
char temp = next->data;
next = next->next;
return temp;
}
void LinkedList::insertFront(char c){
LinkedList *newHead;
newHead->data = c;
newHead->next = next;
next = newHead;
}
char LinkedList::front() const{
return(next->data);
}
答案 0 :(得分:2)
您需要在newHead
中为insertFront
分配内存。
LinkedList *newHead = new LinkedList();