java - 在现有节点之间插入一个节点
问题描述
我有一个插入方法,我需要帮助在两个节点之间插入一个新节点
这是代码:
@Override
public void insert(int index, E data) throws ListOverflowException {
Node<E> curr = startOfNode;
int ctr = 0;
// adds the data in the specified index in the linked list
for (curr = startOfNode; curr !=null; curr = curr.getNext()) {
if (ctr == index) {
Node<E> newNode = new Node<>(data);
curr.setNext(newNode);
newNode.setNext(curr.getNext());
break;
}
ctr++;
}
if (size == maxSize) {
throw new ListOverflowException("Error! Can't add any more nodes");
}
}
这是初始列表:
Item 1 :4
Item 2 :5
Item 3 :6
Item 4 :8
Item 5 :9
Item 6 :null
这是我得到的结果。如您所见,拥有 8 号和 9 号的节点丢失了。如何修改循环以获得所需的结果:
Item 1 :4
Item 2 :5
Item 3 :6
Item 4 :7
Item 5 :null
解决方案
您的第一种方法是有缺陷的,因为您从要插入的索引中省略了所有节点,因此丢失了所有链接。
在您的第二种方法中,您有正确的想法,但是您会得到一个无限循环,因为您curr.getNext()
在插入新节点之后会这样做。解决方法是在插入新节点之前获取节点,临时保存,添加新节点,并将临时保存的节点设置为插入节点的下一个。
它应该看起来像这样:
Node<E> newNode = new Node<>(data);
Node<E> tempNode = curr.getNext(); // retrieve the initially following node
curr.setNext(newNode); // insert the new node
newNode.setNext(tempNode); // reconstruct the link
推荐阅读
- java - 如何在接口默认方法中对新对象创建进行单元测试?
- jenkins - 如何在 groovy 脚本中使用 CURL 命令
- kubernetes - Kubernetes Cron Job 在创建下一个计划之前终止 Pod
- javascript - 在页面离开时通过 AJAX 删除图像
- php - 我可以在 PHP 邮件发送功能中添加紧急状态,以便在用户收到密码时重置密码不会过期吗?
- python - 如何在 os.popen 中传递多个命令
- amp-html - 获取 amp-form 和响应标头的正确方法是什么?
- json - 使用正确的键值对将文本文件转换为 json
- html - 如何在 Jenkins 版本中放置 iframe 或其替代品。2.176.2?
- javascript - 溢出在单词的开头,或在后续文本的末尾,直到下一次出现