我试图将值存储在 C++ 的链表中并打印它们。但我不知道我是否正在编写正确的代码。当我创建一个新的节点插入值打印时,这有效但是。但是当我最后使用 temp 打印所有值时,它不起作用
#include <iostream>
using namespace std;
struct node
{
int val;
node *next;
};
int main()
{
node *temp = new node(); //creating the first node
node *head, *tail;
temp->val= 1; //assigning value to the first node
head = temp; //head contains the address of 1st node
cout<< "head value" <<head << endl;
cout << "head value" << temp << endl;
cout<< "1st value" << temp->val << endl;
cout << "=================================================" << endl;
//============================================second node
temp = temp->next;
temp = new node();
temp->val = 2;
cout << "head value" << head << endl;
cout << "head value" << temp << endl;
cout << "2rd value" << temp->val << endl;
cout << "=================================================" << endl;
//============================================third node
temp = temp->next;
temp = new node();
temp->val = 3;
cout << "head value" << head << endl;
cout << "head value" << temp << endl;
cout << "3rd value" << temp->val << endl;
tail = temp;
temp->next = NULL;
cout<< "=================================================" << endl;
cout<< "value in head" << head->val << endl;
cout << "=================================================" << endl;
cout<< "the value temp is reset to head which is the location of first node" << endl;
cout << "=================================================" << endl;
//temp = NULL;
temp = head; //add of first node is stored in temp
cout<< "the value of head " << head << endl;
cout<< "the value of temp " << temp << endl;
//Problem from this ............................................................
//temp->next = head->next;
cout << "the value of head " << head->next << endl;
cout << "the value of temp " << temp->next << endl;
cout<< "value in head + 1 " << temp->val << endl;
system("pause");
return 0;
}
temp->next
地址不工作时显示的输出
output photo
最佳答案
声明
temp = temp->next;
使 temp
指向与 temp->next
指向的内存相同的内存。这是一个空指针。
然后
temp = new node();
覆盖 temp
的先前值,并使其指向新分配的 node
结构。
以上两个语句没有将新节点链接到列表中。
而是尝试类似的东西
// At this point `temp` is pointing to the last node in the list
// Create a new node and link it into the list
temp->next = new node; // Allocate a new `node` and link it into the list
temp = temp->next; // Make `temp` point to the new node
temp->val = ...; // Set the new value
...
关于c++ - 如何指向链表中的下一个节点并打印值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49051157/