如果您遇到算法困难,只需将其写下来:
// First we have a pointer to a node containing element (elm)
// with possible a next element.
// Graphically drawn as:
// p -> [elm] -> ???
tmp = new Node();
// A new node is created. Variable tmp points to the new node which
// currently has no value.
// p -> [elm] -> ???
// tmp -> [?]
tmp.element = p.element;
// The new node now has the same element as the original.
// p -> [elm] -> ???
// tmp -> [elm]
tmp.next = p.next;
// The new node now has the same next node as the original.
// p -> [elm] -> ???
// tmp -> [elm] -> ???
p.element = y;
// The original node now contains the element y.
// p -> [y] -> ???
// tmp -> [elm] -> ???
p.next = tmp;
// The new node is now the next node from the following.
// p -> [y] -> [elm] -> ???
// tmp -> [elm] -> ???
你有所需的效果,但它可以更有效,我敢打赌你现在可以找到自己。
写这样的东西更清楚:
tmp = new Node();
tmp.element = y;
tmp.next = p;
p = tmp;
如果 p 不可变,这当然不起作用。但是如果 p == NULL,您的算法将失败。
但我想说的是,如果你对算法有问题,就把效果写出来。特别是对于树和链表,你需要确保所有的指针都指向正确的方向,否则你会弄得一团糟。