我想测试下面的代码(适用于非空列表),看看在空列表的情况下会发生什么(在这种情况下,head将为null)。
因此,用于填充列表的代码被注释掉了。
但由于一些奇怪的原因,print_nodes()中的NULL测试似乎不起作用。我添加了一些调试cout调用来查看(并且还使用gdb检查)但是虽然值确实看起来是NULL,但任何if语句似乎都没有正确地测试等价...
任何想法为什么?
非常感谢! #include <iostream>
using namespace std;
struct node {
char dat;
node *nextPtr;
};
//inserts new node and returns pointer
node* new_node(char data, node* prevNode);
//adds a new node at the head ofthe list
void new_head (node *head_, char dat_);
//inserts new node after *before
void insert_node (node *before, char dat_);
//runs through and prints the list - requires first node (head)
void print_nodes (node *head);
int main() {
cout <<endl << endl;
cout << endl << "*******************RUN******************" <<endl <<endl;
node* head = NULL;
if (head == NULL) {
cout << "head null"; //this works here
}
//head non-standard
// node* head = new node;
// head->dat ='a';
/*
node* b = new_node('b', head);
node* c = new_node('c', b);
node* d = new_node('d', c);
node* e = new_node('e', d);
node* f = new_node('f', e);
*/
print_nodes(head);
insert_node(head,'N');
print_nodes(head);
cout << endl << "*******************END RUN******************" <<endl;
return 0;
}
node* new_node(char data, node* prevNode) {
node* tempPtr = new node;
tempPtr->dat = data;
tempPtr->nextPtr = NULL; //standard
prevNode->nextPtr = tempPtr;
return tempPtr;
}
void new_head (node *head_, char dat_) {
}
void insert_node (node *before, char dat_) {
node* tempPtr = new node;
tempPtr->dat = dat_;
tempPtr->nextPtr = before->nextPtr;
before->nextPtr = tempPtr;
}
void print_nodes (node *head) {
node* tempPtr = head;
cout << "\nPrinting nodes..." <<endl;
if (tempPtr == NULL) { //this test is not working.. why?
cout << "tempPtr is NULL";
return;
} else { //only run in the non null case
for (tempPtr; tempPtr != NULL; tempPtr = tempPtr->nextPtr) {
cout << "Current node content: " << tempPtr->dat <<endl;
}
}
}
答案 0 :(得分:2)
你有一个问题:没有分配头,但是insert访问它的“下一个元素”:
before->nextPtr = tempPtr;
head
作为before
传入,而您没有为head
分配内存。因此,您在此处取消引用NULL指针。
可能是您的应用程序因此崩溃了,并且由于cout
被缓冲而没有完成打印到cout
的打印输出?
尝试:
insert
cout
更改为cerr
(无缓冲)报告这些变化的结果。
答案 1 :(得分:0)
该代码适用于我在Windows上使用g ++ 4.4.1。由于代码中的其他问题,将显示该消息然后崩溃。您可能没有看到该消息,因为崩溃发生在包含消息的输出缓冲区被刷新之前。
通常,将诊断消息写入标准错误(cerr)而不是标准输出是个好主意,因为错误流没有缓冲。
答案 2 :(得分:0)
在插入前分配头部:
node * head = new node;
memset(head, 0, sizeof(node));