考慮以下代碼:C++路過Refrence或值指針
#include <iostream>
using namespace std;
struct Node
{
int x;
Node *next;
};
void append(Node* h1, Node* h2)
{
cout << h1 << ":" << h2;
cout << endl;
Node *ptr;
ptr = h1;
while (ptr->next != NULL)
{
ptr = ptr->next;
}
ptr->next = h2;
}
void insertAtHead(Node* head, int k)
{
Node *tmp = new Node;
tmp -> x = k;
tmp -> next = head;
head = tmp;
}
int main()
{
Node *n1 = new Node;
n1->x = 1;
n1->next = NULL;
Node *n2 = new Node;
n2->x = 2;
n2->next = NULL;
Node *n3 = new Node;
n3->x = 3;
n3->next = n2;
cout << n1 << ":" << n3;
cout << endl;
append(n1,n3);
insertAtHead(n1,4);
while(n1 != NULL)
{
cout << n1->x;
n1 = n1->next;
}
cout << endl;
}
的附加功能的工程,即使我們有Node* h1
但即使我們有相同的Node* head.
爲什麼insertAtHead不起作用?
我們需要Node* &head
爲appendAtHead工作。爲什麼?
所以副本正在以追加改性但我們仍然看到修改後的結果。爲什麼? –