问题
In the following code:
void insert(Node *& aNode, int x) {
if (!aNode) {
aNode = new Node(x);
aNode->next = aNode;
return;
}
Node *p = aNode;
Node *prev = NULL;
do {
prev = p;
p = p->next;
if (x <= p->data && x >= prev->data) break; // For case 1)
if ((prev->data > p->data) && (x < p->data || x > prev->data)) break; // For case 2)
} while (p != aNode); // when back to starting point, then stop. For case 3)
Node *newNode = new Node(x);
newNode->next = p;
prev->next = newNode;
}
What is Node *& aNode?
How should I use this function, I mean, which type of parameter should I pass?
回答1:
I think this code is C++, not C, and Node *&aNode is a reference to a pointer to a Node, so you would pass a Node* to the function, and function would make a reference to that (so the memory location your Node* is pointing to can change).
You may find the Wikipedia article on References (C++) interesting.
A simple example:
#include <iostream>
void addOneToValue(int num) {
++num;
}
void addOneToRef(int &num) {
++num;
}
int main() {
int num = 0;
// print 0
std::cout << num << std::endl;
// print 0 again (addOneToValue() has no effect)
addOneToValue(num);
std::cout << num << std::endl;
// print 1 (addOneToRef() changes the value of num)
addOneToRef(num);
std::cout << num << std::endl;
}
@crashmstr's comment reminded me that I should say how they're different from pointers. Wikipedia does a better job that I could though:
- It is not possible to refer directly to a reference object after it is defined; any occurrence of its name refers directly to the object it references.
- Once a reference is created, it cannot be later made to reference another object; it cannot be reseated. This is often done with pointers.
- References cannot be null, whereas pointers can; every reference refers to some object, although it may or may not be valid.
- References cannot be uninitialized. Because it is impossible to reinitialize a reference, they must be initialized as soon as they are created. In particular, local and global variables must be initialized where they are defined, and references which are data members of class instances must be initialized in the initializer list of the class's constructor.
- Most compilers will support a null reference without much complaint, crashing only if you try to use the reference in some way.
来源:https://stackoverflow.com/questions/7906546/what-is-node-anode