我对C++比较陌生,我遇到了一个我实际上不理解的问题。我的代码创建一个链表。它实际上比这更长,但为了这个问题我砍了下来。C++删除操作符
当我运行的代码,它增加了三个节点,然后当它与URI b
删除的节点,它调用delete
运营商和最终删除节点,但随后似乎回到delete
操作(当我通过它时),它杀死了我的整个列表。
#include <iostream>
#include <string>
#include <cstdlib>
#include <cstdio>
using namespace std;
class CLinkedList
{
protected:
class ip_uri_store
{
public:
string uri, ip;
ip_uri_store* next;
ip_uri_store(const string& URI, const string& IP) {uri = URI, ip = IP, next = NULL;}
};
typedef ip_uri_store* nodeAddress;
nodeAddress head;
void AddNode(const string&, const string&, nodeAddress);
void DeleteNode(const string&, nodeAddress, nodeAddress);
public:
CLinkedList() {head = NULL;}
void AddNode(const string& URI, const string& IP) {AddNode(URI, IP, head);}
void DeleteNode(const string& URI) {DeleteNode(URI, head, head);}
};
void CLinkedList::AddNode(const string& URI, const string& IP, nodeAddress node)
{
nodeAddress temp = new ip_uri_store(URI, IP);
temp->uri = URI;
temp->ip = IP;
temp->next = head;
head = temp;
}
void CLinkedList::DeleteNode(const string& URI, nodeAddress node, nodeAddress behindNode)
{
if(node)
{
if(!node->uri.compare(URI))
node == head ? head = head->next : behindNode->next = node->next;
else
DeleteNode(URI, node->next, node);
delete node;
}
}
int main(int argc, char* argv[])
{
CLinkedList lList;
lList.AddNode("a", "1");
lList.AddNode("b", "2");
lList.AddNode("c", "3");
lList.DeleteNode("b");
return 0;
}
即三元条件运算符的严重滥用。 –
考虑到他是新手,代码似乎从随机站点复制... – Blindy
我没有复制它。这是我的代码。新的我的意思是几个月。我一直在阅读很多关于C++的知识... –