c++ - 在 C++ 中反转单链表:堆栈中的指针
问题描述
我有一个由节点组成的链表,一个有 2 个成员的类:
Node* next;
int val;
名单如下:
[head:0] -> [1] -> [2] -> [3] -> nullptr
我写了一个函数来反转这个列表。
void reverseList(Node* head) {
Node* m = head->next;
head->next = nullptr;
while (m) {
Node* n = m;
m = n->next;
n->next = head;
head = n;
printNode(head);
}
}
int main() {
// Create linked list here
reverseList(&head);
cout << "FXN ENDS" << endl;
printNode(&head);
}
这将打印:
1 0
2 1 0
3 2 1 0
FXN ENDS
0
我知道一旦退出Node* n
就会被删除,因为是在堆栈上分配的。但是通过设置不应该指向的内存即使在函数退出后仍然在堆中,因此仍然指向有效内存?reverseNode
n,m
head=n;
n
head
谢谢你。
解决方案
我知道一旦退出 While 循环,Node* n 就会被删除,因为 n 是在堆栈上分配的。但是通过设置 head=n; 即使退出 While 循环,n 指向的内存不应该仍然在堆中,因此 head 仍然指向有效内存吗?
Pointers are just like variables, when it comes to passing them to functions. The default behavior is to copy the pointer. If you actually want to change the argument passed to the function, you need to take it by reference:
void reverseList(Node* &head) {
推荐阅读
- nginx - Nginx 使用子域访问我的网站会下载文件
- listview - 如何在 Flutter 中使用 StatelessWidget 和提供程序以编程方式滚动 ListView?
- react-native - 试图安装博览会
- laravel - Laravel 7.x 刀片 {!! !}} 转义了问号符号 (?) 虽然它不包含在 php htmlspecialchars 中
- javascript - 在JS中循环构造函数不起作用
- mysql - 从 Azure Database for MYSQL 复制到 VM MYSQL 中的 Mysql 数据
- javascript - express mongodb查找查询结果空数组
- python - Selenuim:返回 NoSuchElementException:消息:在 Safari 上的机器人框架中使用关键字时
- java - Java :: 比较 ronded 双打不起作用
- javascript - 承诺中的内存泄漏