C++链接列表运行时错误:未处理的异常 - 写入位置冲突

发布于 2024-09-18 04:14:52 字数 1536 浏览 4 评论 0原文

我正在尝试用 C++ 构建自己的链表实现。我的代码正在编译,但显然我的指针引用无效的内存地址存在一些问题。

这是我的实现:

#include <iostream>
#include <string>

using namespace std;

class Node
{
    private:
        string _car;
        Node* nextNode;

    public:
        void setCar(string car)
        {
            _car = car;
        }

        string getCar()
        {
            return _car;
        }

        void setNextNode(Node* node)
        {
            nextNode = node;
        }

        Node* getNextNode()
        {
            return nextNode;
        }
};

Node* findLast(Node* node)
{
    Node* nodeOut = NULL;
    while (node->getNextNode() != NULL)
    {
        nodeOut = node->getNextNode();
    }
    return nodeOut;
}

string toString(Node* node)
{
    string output = "";
    while (node->getNextNode() != NULL)
    {
        output += node->getCar() + " ";
        node = node->getNextNode();
    }
    return output;
}

int main()
{
    char xit;
    //ser head node to NULL
    Node* headNode = NULL;

    //create node 1
    Node* node1 = new Node();
    node1->setCar("Mercedes");

    //create node 2
    Node* node2 = new Node();
    node2->setCar("BMW");

    //set node links
    headNode->setNextNode(node1);
    node1->setNextNode(node1);
    node2->setNextNode(node2);

    headNode = node1;

    Node* lastNode = findLast(headNode);

    lastNode->setNextNode(NULL);

    cout << toString(headNode) << endl;

    //pause console
    cin >> xit;
}

I am trying to build my own implementation of a linked list in C++. My code is compiling but apparently there is some issue with my pointers referring to invalid memory addresses.

Here is my implementation:

#include <iostream>
#include <string>

using namespace std;

class Node
{
    private:
        string _car;
        Node* nextNode;

    public:
        void setCar(string car)
        {
            _car = car;
        }

        string getCar()
        {
            return _car;
        }

        void setNextNode(Node* node)
        {
            nextNode = node;
        }

        Node* getNextNode()
        {
            return nextNode;
        }
};

Node* findLast(Node* node)
{
    Node* nodeOut = NULL;
    while (node->getNextNode() != NULL)
    {
        nodeOut = node->getNextNode();
    }
    return nodeOut;
}

string toString(Node* node)
{
    string output = "";
    while (node->getNextNode() != NULL)
    {
        output += node->getCar() + " ";
        node = node->getNextNode();
    }
    return output;
}

int main()
{
    char xit;
    //ser head node to NULL
    Node* headNode = NULL;

    //create node 1
    Node* node1 = new Node();
    node1->setCar("Mercedes");

    //create node 2
    Node* node2 = new Node();
    node2->setCar("BMW");

    //set node links
    headNode->setNextNode(node1);
    node1->setNextNode(node1);
    node2->setNextNode(node2);

    headNode = node1;

    Node* lastNode = findLast(headNode);

    lastNode->setNextNode(NULL);

    cout << toString(headNode) << endl;

    //pause console
    cin >> xit;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

寄居者 2024-09-25 04:14:52

您需要重新查看您的代码。

头节点 = 节点1;

该赋值应该在访问实例 headNode 的任何成员函数之前完成。
最初,您已将 NULL 分配给该指针。
创建node1后,您将设置为无效实例的headNode。这就是崩溃的原因。
确保你的目标,然后尝试在纸上做一些粗略的工作,制作一些图表,这样你会更清楚你到底想要实现什么。
为什么要设置NextNode???我不明白你想达到什么目的。首先要明确。

根据我的理解,这段代码应该像下面这样实现。

#include <iostream> 
#include <string> 

using namespace std; 

class Node 
{ 
    private: 
        string _car; 
        Node* nextNode; 

    public: 
        void setCar(string car) 
        { 
            _car = car; 
        } 

        string getCar() 
        { 
            return _car; 
        } 

        void setNextNode(Node* node) 
        { 
            nextNode = node; 
        } 

        Node* getNextNode() 
        { 
            return nextNode; 
        } 
}; 

Node* findLast(Node* node) 
{ 
    Node* nodeOut = node->getNextNode(); 
    while ( nodeOut->getNextNode()!= NULL) 
    { 
        nodeOut = nodeOut->getNextNode(); 
    } 
    return nodeOut; 
} 

string toString(Node* node) 
{ 
    string output = ""; 
    while (node != NULL) 
    { 
        output += node->getCar() + " "; 
        node = node->getNextNode(); 
    } 
    return output; 
} 

int main() 
{ 
    char xit; 
    //ser head node to NULL 
    Node* headNode = NULL; 

    //create node 1 
    Node* node1 = new Node(); 
    node1->setCar("Mercedes"); 
    node1->setNextNode(NULL);//Make null to each next node pointer 

    headNode = node1; //assign the node1 as headNode

    //create node 2 
    Node* node2 = new Node(); 
    node2->setCar("BMW"); 
    node2->setNextNode(NULL);

    //set node links 
     node1->setNextNode(node2);




    Node* lastNode = findLast(headNode); 

    lastNode->setNextNode(NULL); 

    cout << toString(headNode) << endl; 

    //pause console 
    cin >> xit; 
}

希望它对在 C++ 中实现链接列表的初学者有用。

You need to relook at your code.

headNode = node1;

This assignment should be done before accesing any member function of the instance headNode.
Intially you have assigned NULL to this pointer.
After creating node1 you are setting to headNode that is invalid instance. This is the cause of crash.
Be ensure with your objective and then try to implement do some rough work on paper , make some diagram that way you would be more clear that what you are exactly trying to achive.
why setNextNode ??? i don't undeerstand what you wanted to achieve. be clear first.

As per my undertanding this code should be implemented like below..

#include <iostream> 
#include <string> 

using namespace std; 

class Node 
{ 
    private: 
        string _car; 
        Node* nextNode; 

    public: 
        void setCar(string car) 
        { 
            _car = car; 
        } 

        string getCar() 
        { 
            return _car; 
        } 

        void setNextNode(Node* node) 
        { 
            nextNode = node; 
        } 

        Node* getNextNode() 
        { 
            return nextNode; 
        } 
}; 

Node* findLast(Node* node) 
{ 
    Node* nodeOut = node->getNextNode(); 
    while ( nodeOut->getNextNode()!= NULL) 
    { 
        nodeOut = nodeOut->getNextNode(); 
    } 
    return nodeOut; 
} 

string toString(Node* node) 
{ 
    string output = ""; 
    while (node != NULL) 
    { 
        output += node->getCar() + " "; 
        node = node->getNextNode(); 
    } 
    return output; 
} 

int main() 
{ 
    char xit; 
    //ser head node to NULL 
    Node* headNode = NULL; 

    //create node 1 
    Node* node1 = new Node(); 
    node1->setCar("Mercedes"); 
    node1->setNextNode(NULL);//Make null to each next node pointer 

    headNode = node1; //assign the node1 as headNode

    //create node 2 
    Node* node2 = new Node(); 
    node2->setCar("BMW"); 
    node2->setNextNode(NULL);

    //set node links 
     node1->setNextNode(node2);




    Node* lastNode = findLast(headNode); 

    lastNode->setNextNode(NULL); 

    cout << toString(headNode) << endl; 

    //pause console 
    cin >> xit; 
}

Hope it would be useful for the beginner who implement ing the linklist in c++.

不顾 2024-09-25 04:14:52

重读一下:

node1->setNextNode(node1);
node2->setNextNode(node2);

......并想想你在这里做什么。

如果您要编写链表代码,我建议至少查看 std::list接口。现在,您的接口处于如此低的级别,以至于您至少可以直接操作指针。

Reread this:

node1->setNextNode(node1);
node2->setNextNode(node2);

...and think about what you're doing here.

If you're going to write linked-list code, I'd advise at least looking at the interface for std::list. Right now, you're interface is at such a low level that you'd be at least as well off just manipulating pointers directly.

空城缀染半城烟沙 2024-09-25 04:14:52

实际错误的原因是:

headNode->setNextNode(node1);

headNode 仍设置为 NULL,因此您取消引用 NULL 指针。正如 Jerry 所指出的,您还要求节点指向自身,这不是您想要的。

如果将汽车作为构造函数参数会更清晰。

The cause of your actual error is:

headNode->setNextNode(node1);

headNode is still set to NULL, thus you're dereferencing a NULL pointer. As noted by Jerry, you're also calling having nodes point to themselves, which is not what you want.

It would be cleaner if you took the car as a constructor parameter.

静水深流 2024-09-25 04:14:52

当您分配一个新的Node时,指针nextNode并未初始化,它只是随机垃圾。您需要将其显式设置为 NULL(可能在 Node 的构造函数中)。

另外,我假设您知道标准 C++ 库有一个内置的链接列表,您这样做只是为了学习;-)

When you allocate a new Node, the pointer nextNode is not initialized, it's just random junk. You will need to explicitly set it to NULL (probably in a constructor for Node).

Also, I assume you know that the standard C++ library has a linked list built in and you're just doing this for learning ;-)

故事↓在人 2024-09-25 04:14:52

感谢您的所有建议,这是我在主要清理后的最终代码:

// LinkedListProject.cpp : main project file.

#include "stdafx.h"

#include <iostream>
#include <string>

using namespace System;
using namespace std;

class Node
{
    public:
        Node()
            :_car(""), _nextNode(NULL)
        {
        }

        void SetCar(string car)
        {
            _car = car;
        }

        string GetCar()
        {
            return _car;
        }

        void SetNextNode(Node *node)
        {
            _nextNode = node;
        }

        Node * GetNextNode()
        {
            return _nextNode;
        }

    private:
        string _car;
        Node *_nextNode;
};

string GetData();
Node * AddNode(Node *firstNode, Node *newNode);
Node * DeleteNode(Node *firstNode, string nodeData);
void PrintNodes(Node *firstNode);

int main(int argc, char *argv[])
{
    string command = "";
    string data = "";
    Node *firstNode = NULL;

    do
    {
        cout << "Enter command: ";
        cin >> command;

        if(command == "add")
        {
            data = GetData();

            Node *newNode = new Node();
            newNode->SetCar(data);

            firstNode = AddNode(firstNode, newNode);
        }
        else if(command == "delete")
        {
            data = GetData();

            firstNode = DeleteNode(firstNode, data);
        }
        else if(command == "print")
        {
            PrintNodes(firstNode);
        }
    } while(command != "stop");

    return 0;
}

string GetData()
{
    string data = "";

    cout << "Enter data: ";
    cin >> data;

    return data;
}

Node * AddNode(Node *firstNode, Node *newNode)
{
    //add new node to front of queue
    newNode->SetNextNode(firstNode);
    firstNode = newNode;

    return firstNode;
}

Node * DeleteNode(Node *firstNode, string nodeData)
{
    Node *currentNode = firstNode;
    Node *nodeToDelete = NULL;

    if (firstNode != NULL)
    {
        //check first node
        if(firstNode->GetCar() == nodeData)
        {
            nodeToDelete = firstNode;
            firstNode = firstNode->GetNextNode();
        }
        else //check other nodes
        {
            while (currentNode->GetNextNode() != NULL &&
                   currentNode->GetNextNode()->GetCar() != nodeData)
            {
                currentNode = currentNode->GetNextNode();
            }

            if (currentNode->GetNextNode() != NULL &&
                currentNode->GetNextNode()->GetCar() == nodeData)
            {
                nodeToDelete = currentNode->GetNextNode();
                currentNode->SetNextNode(currentNode->GetNextNode()->GetNextNode());
            }
        }

        if(nodeToDelete != NULL)
        {
            delete nodeToDelete;
        }
    }

    return firstNode;
}

void PrintNodes(Node *firstNode)
{
    Node *currentNode = firstNode;
    while(currentNode != NULL)
    {
        cout << currentNode->GetCar() << endl;
        currentNode = currentNode->GetNextNode();
    }
}

Thanks for all the suggestions, here is my final code after major cleanup:

// LinkedListProject.cpp : main project file.

#include "stdafx.h"

#include <iostream>
#include <string>

using namespace System;
using namespace std;

class Node
{
    public:
        Node()
            :_car(""), _nextNode(NULL)
        {
        }

        void SetCar(string car)
        {
            _car = car;
        }

        string GetCar()
        {
            return _car;
        }

        void SetNextNode(Node *node)
        {
            _nextNode = node;
        }

        Node * GetNextNode()
        {
            return _nextNode;
        }

    private:
        string _car;
        Node *_nextNode;
};

string GetData();
Node * AddNode(Node *firstNode, Node *newNode);
Node * DeleteNode(Node *firstNode, string nodeData);
void PrintNodes(Node *firstNode);

int main(int argc, char *argv[])
{
    string command = "";
    string data = "";
    Node *firstNode = NULL;

    do
    {
        cout << "Enter command: ";
        cin >> command;

        if(command == "add")
        {
            data = GetData();

            Node *newNode = new Node();
            newNode->SetCar(data);

            firstNode = AddNode(firstNode, newNode);
        }
        else if(command == "delete")
        {
            data = GetData();

            firstNode = DeleteNode(firstNode, data);
        }
        else if(command == "print")
        {
            PrintNodes(firstNode);
        }
    } while(command != "stop");

    return 0;
}

string GetData()
{
    string data = "";

    cout << "Enter data: ";
    cin >> data;

    return data;
}

Node * AddNode(Node *firstNode, Node *newNode)
{
    //add new node to front of queue
    newNode->SetNextNode(firstNode);
    firstNode = newNode;

    return firstNode;
}

Node * DeleteNode(Node *firstNode, string nodeData)
{
    Node *currentNode = firstNode;
    Node *nodeToDelete = NULL;

    if (firstNode != NULL)
    {
        //check first node
        if(firstNode->GetCar() == nodeData)
        {
            nodeToDelete = firstNode;
            firstNode = firstNode->GetNextNode();
        }
        else //check other nodes
        {
            while (currentNode->GetNextNode() != NULL &&
                   currentNode->GetNextNode()->GetCar() != nodeData)
            {
                currentNode = currentNode->GetNextNode();
            }

            if (currentNode->GetNextNode() != NULL &&
                currentNode->GetNextNode()->GetCar() == nodeData)
            {
                nodeToDelete = currentNode->GetNextNode();
                currentNode->SetNextNode(currentNode->GetNextNode()->GetNextNode());
            }
        }

        if(nodeToDelete != NULL)
        {
            delete nodeToDelete;
        }
    }

    return firstNode;
}

void PrintNodes(Node *firstNode)
{
    Node *currentNode = firstNode;
    while(currentNode != NULL)
    {
        cout << currentNode->GetCar() << endl;
        currentNode = currentNode->GetNextNode();
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文