在 C++ 中反转单链表:堆栈中的指针

Reversing a singly linked list in C++: pointer in the stack

我有一个由节点组成的链表,一个 class 有 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

我知道一旦 reverseNode 退出,Node* n 就会被删除,因为 n,m 是在堆栈上分配的。但是通过设置 head=n;,即使在函数退出后,n 指向的内存不应该仍然在堆中,因此 head 仍然指向有效内存吗?

谢谢。

I know that Node* n gets deleted once the While loop is exited, since n is allocated on the stack. But by setting head=n; shouldn't the memory that n points to still be in the heap even after the While loop is exited and hence head still points to valid memory?

在将指针传递给函数时,指针就像变量一样。默认行为是 copy 指针。如果你真的想改变传递给函数的参数,你需要引用它:

void reverseList(Node* &head) {