如果遇到问题,只需写下来即可:
// 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,则您的算法将失败。
但是我要说的是,如果您对算法有疑问,只需写下效果即可。尤其是对于树和链表,您需要确保所有指针都指向严格的方向,否则会造成混乱。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)