首页 > 解决方案 > 在 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就会被删除,因为是在堆栈上分配的。但是通过设置不应该指向的内存即使在函数退出后仍然在堆中,因此仍然指向有效内存?reverseNoden,mhead=n;nhead

谢谢你。

标签: c++stackheap-memory

解决方案


我知道一旦退出 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) {

推荐阅读