c++ - 既没有节点也没有数组的链表

标签 c++ class object linked-list singly-linked-list

我的教授给了我们这个 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/

相关文章:

c++ - for循环条件中的函数调用?

c++ - 表面上等效的表达式 (class)A a; 和 (class)A a{}; 之间的区别

javascript - 根据属性从对象数组中过滤对象

c++ - 多态是实现这一目标的最佳方法吗? (关于派生类中的函数调用)

c++ - Arduino 子串不起作用

c++ - 从 sizeof 自动扣除的类型在 Visual Studio C++ 和 GCC 之间不同

c++ - 子类递归方法调用

Java创建多个内部类对象并拥有自己的实例

c++ - 双重转换会解决它,但 C++ 中没有这样的事情,对吗?

c++ - 重载赋值运算符,rhs是函数调用