您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

在恒定时间内将节点插入链表?

在恒定时间内将节点插入链表?

如果遇到问题,只需写下来即可:

// 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,则您的算法将失败。

但是我要说的是,如果您对算法有疑问,只需写下效果即可。尤其是对于树和链表,您需要确保所有指针都指向严格的方向,否则会造成混乱。

其他 2022/1/1 18:43:18 有467人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶