我的教授给了我们这个 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);
}
最佳答案
需要在insertFront
中为newHead
分配内存。
LinkedList *newHead = new LinkedList();
关于c++ - 既没有节点也没有数组的链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32900234/