在尝试将节点添加到链接列表时,我做错了什么?

时间:2017-05-02 07:42:56

标签: c++ memory linked-list

我正在用C ++创建一个简单的Snake游戏。我可以打印出地图([10x10]字符数组),我可以在一个随机的地方显示一个水果(例如:[2,7]通过调用它的构造函数),但是我在添加新体时遇到了很多问题蛇的部分(它不能生长)。我认为使用蛇本身的链表是个好主意。我可以肯定地使用一些帮助,下面是我的代码:

snake.h

class Snake{
protected:
    struct snakeBody {
        char bodyPart;
        snakeBody* next;
    }typedef snakeBody;

    snakeBody* firstNode;
    snakeBody* lastNode;
public:
    Snake();
    void grow();
    void displaySnake();
    ~Snake();

}

snake.cpp

Snake::Snake(){
    /*Linked list - first and last nodes.*/
    lastNode = new snakeBody;
    lastNode = NULL;
    firstNode = new snakeBody;
    firstNode->bodyPart = '8';
    firstNode->next = lastNode;
}

void Snake::grow() {
    snakeBody* tmp = new snakeBody;
    if (firstNode->next == lastNode) {
        firstNode->next = tmp;
        tmp->bodyPart = '#';
        cout << tmp->bodyPart;
    }
    else {
        /*Navigate to the last NOT NULL element of the list.*/
        while (firstNode->next != NULL) {
            tmp = firstNode->next;
        }

        tmp->bodyPart = '#';
        cout << tmp->bodyPart;
        tmp->next = lastNode;
    }
}

void Snake::displaySnake() {
    snakeBody* tmp2 = new snakeBody;
    tmp2 = firstNode;
    while (tmp2->next != NULL) {
        tmp2 = tmp2->next;
        cout << tmp2->bodyPart;
    }
}

Snake::~Snake() {
    cout << "Snake killed.";
}

如何释放蛇的整个身体(从头到脚的每个部分)的记忆?提前谢谢!

1 个答案:

答案 0 :(得分:0)

void Snake::grow() {
snakeBody* new_node=new snakeBody();
snakeBody* tmp=firstNode;
if (firstNode->next == NULL) {
    firstNode->next = new_node;
    new_node->bodyPart = '#';
    new_node->next=NULL;

}
else {
    /*Navigate to the last NOT NULL element of the list.*/
    while (tmp->next != NULL) {
        tmp = tmp->next;
    }
    tmp->next=new_node;
    new_node->bodyPart = '#';
    new_node->next = NULL;
}
}

void Snake::displaySnake() {
snakeBody* tmp2 = firstNode;
while (tmp2!= NULL) {
    cout << tmp2->bodyPart<<endl;
    tmp2 = tmp2->next;

}
}

我没有在代码中使用lastNode,你可以修改它。