这个链表问题在哪里呀?怎么运行不正常?
我用Dev-C++编写链表程序,运行以后有问题。#include <iostream>
#include <string>
/************************************************
* linked_list -- Class to handle a linked list *
* containing a list of strings. *
* *
* Member functions: *
* add -- Add an item to the list *
* is_in -- Check to see if a string is *
* in the list. *
************************************************/
class linked_list {
private:
/*
* Node in the list
*/
struct node {
// String in this node
std::string data;
// Pointer to next node
struct node *next;
};
//First item in the list
struct node *first;
public:
// Constructor
linked_list(void): first(NULL) {};
// Destructor
~linked_list();
private:
// No copy constructor
linked_list(const linked_list &);
// No assignment operator
linked_list& operator = (const linked_list &);
public:
// Add an item to the list
void add(
// Item to add
const std::string &what
) {
// Create a node to add
struct node *new_ptr = new node;
// Add the node
new_ptr->next = first;
new_ptr->data = what;
first = new_ptr;
}
bool is_in(const std::string &what);
};
/************************************************
* is_in -- see if a string is in a *
* linked list. *
* *
* Returns true if string's on the list, *
* otherwise false. *
************************************************/
bool linked_list::is_in(
// String to check for
const std::string &what
) {
/* current structure we are looking at */
struct node *current_ptr;
current_ptr = first;
while (current_ptr != NULL) {
if (current_ptr->data == what)
return (true);
current_ptr = current_ptr->next;
}
return (false);
}
/************************************************
* linked_list::~linked_list -- Delete the *
* data in the linked list. *
************************************************/
linked_list::~linked_list(void) {
while (first != NULL) {
delete first;
first = first->next;
}
}
int main() {
linked_list list; // A list to play with
list.add("Sam");
list.add("Joe");
list.add("Mac");
if (list.is_in("Harry"))
std::cout << "Harry is on the list\n";
else
std::cout << "Could not find Harry\n";
return (0);
}这段是代码。调试过程中到最后一步,跳出一个窗口
如果直接执行返回值为3221226356
请问出什么问题了?怎么解决?
大哥,既然DELETE,就不要再用他了好吗? 你看你的析构函数,已经delete了first了 还要去找他的next 这样不太好吧,你要不先找个中间指针变量把他的next装好了再去delete他,然后把first赋值。没调试过你的程序,只有先给出这样一个答案。 天下无敌丑爸爸 发表于 2014-1-4 20:41 static/image/common/back.gif
大哥,既然DELETE,就不要再用他了好吗? 你看你的析构函数,已经delete了first了 还要去找他的next 这样不 ...
谢谢哦,我把first = first->next;和delete first;颠倒了次序就好了。{:5_95:} 路过看看= = 纠正一下这个问题的答案。我上面说的只颠倒两个语句次序的做法不能说是正确的。也许当时测试的编译器忽略了这个问题。那就是当最后一个first = first->next;的时候,first就已经是NULL了,于是就要delete一个已经是NULL的节点。这不科学。应该像下面这样做:linked_list::~linked_list() {
while (first != NULL) {
node * prev = first;
delete first; //NOTICE: the link should be reset before first is deleted.
first = prev->next;
}
}
页:
[1]