链表—向链表中添加元素
2019-07-15 本文已影响0人
尤奇勤_三月
冰冻非一日之寒
添加剂元素之前

向链表头部添加元素:
现在有一个链表,头部结点,为head,假设要将结点node添加到链表首部

直接将node.next指向head,然后改变链表首部为node

这样,就完成了node插入到链表的首部了。

java实现

向index位置处添加元素:
假设向结点为2处添加结点node

找到2结点处的前一个结点pre,即1结点,并node.next = pre.next

然后,pre.next = node

这样,就完成了结点node的添加。
这个过程的关键,是找到要添加结点的前一个结点。

另外,
node.next = pre.next;pre.next = node这两句代码顺序是不能颠倒的。
注意,假如要添加的地方是第一个结点处,就不能使用这种方法了,因为第一个结点是没有前一个结点的。
java实现

向链表尾部添加元素:
直接调用add()函数即可
