链接列表编码如下。这是非常基本的内容,但是我不太了解。
#include <iostream>
#include <string>
#include <iomanip>
#include <cstdlib>
#include <time.h>
#include <fstream>
using namespace std;
int main()
{
struct node {
int data;
node* next;
};
node* head = NULL;
node* cur = NULL;
string condition = "Yes";
while (condition != "No") {
cout << "What is the next value of the linked list " << endl;
int value;
cin >> value;
node* newnode = new node;
newnode->data = value;
newnode->next = NULL;
if (head == NULL) {
head = newnode;
cur = newnode;
newnode = NULL;
}
else {
cur->next = newnode;
cur = newnode;
}
cin >> condition;
}
cout << "These are your values " << endl;
int i = 0;
while (i < 7) {
cout << head->data << endl;
head = head->next;
i++;
}
}
在函数中,当它应该向链表中添加新值时,else {
cur->next = newnode;
cur = newnode;
}
但是据我了解,如果我在第一行中更改newnode的指针旁边的值,那么我在第二行中更改整个节点是否会覆盖呢?这是否意味着该节点丢失了下一个节点的地址,即它在cur-> next中的地址为零?有人可以向我解释这是如何工作的吗?
最佳答案
var cur只是一个指针,它第一次指向最后一个newnode,而cur-> next'address是当前的newnode,执行第二行时,cur地址改变了,但是last newnode没有变化,因此cur-> next不会为零,它指向当前的newnode。
关于c++ - 有人可以向我解释此链接列表如何工作吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/62505475/