简体   繁体   English

我需要一些帮助来理解一些涉及 C++ 中的链接列表的代码

[英]I need some help understanding some code involving Linked Lists in C++

This might be a very dumb question.这可能是一个非常愚蠢的问题。 I have an assignment to create a new node and add a value to it.我有一个任务来创建一个新节点并为其添加一个值。 I've been looking for help online and I came across this code:我一直在网上寻求帮助,我遇到了这段代码:

head = new(struct node);

I assume it is a way of creating a new node and assigning it to head, right?我认为这是一种创建新节点并将其分配给 head 的方法,对吧? Is it just a simpler way of writing this?它只是一种更简单的编写方式吗?

node *new_node = new node;
head = new_node;

Thanks谢谢

That is correct.那是对的。 head = new(struct node); is using the assingment operator and safes you one line compared to正在使用 assingment 运算符,并且与

node *new_node = new node; head = new_node; . .

I am not sure but I think modern compilers even optimize both inputs to the same assembly code, but you acutually should use head = new(struct node);我不确定,但我认为现代编译器甚至将两个输入都优化为相同的汇编代码,但您实际上应该使用head = new(struct node); because it is more readable.因为它更具可读性。

The struct is unnecessary:struct是不必要的:

head = new node;

is all you need to write.就是你需要写的所有东西。 Conventionally you'd add brackets to be more consistent with classes with parameters in their constructors:通常,您会添加括号以与在其构造函数中具有参数的类更加一致:

head = new node();

This is identical to your second example of creating in a temporary value then copying into head .这与您在临时值中创建然后复制到head的第二个示例相同。 Most compilers will optimise away the temporary value.大多数编译器会优化掉临时值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM