java - 将一个节点插入到一个排序的整数链表中,这样该列表仍然与最终成员一起排序以供下一个
问题描述
在 Java 中,如果所有节点都有一个用于 next 的最终成员变量,那么您将如何编写一个方法将节点插入到整数的排序链表中,以使列表仍然保持排序状态,因此您无法更改它们?
解决方案
当下一个链接最终确定时:
唯一的理论方法是在列表前面添加一个新节点并移动数据:
void insertSorted(MyList list, int data) {
list.head = new Node(0, list.head); // Insert in front;
Node prior = list.head;
// Invariant condition: prior points to a node (not null) and soon data >= prior.data
Node current = prior.next;
while (current != null) {
if (data < current.data) {
break;
}
prior.data = current.data; // Shift smaller
prior = current;
current = current.next;
}
prior.data = data;
}
insert: d
list.head: a ; b ; c ; e ; f ; g
--------------------------------------
list.head: X ; a ; b ; c ; e ; f ; g
a <-´ | |
b <-´ |
c <-´
d
是面试题吗?看起来很学术。
推荐阅读
- apache-spark - spark无法从aws读取
- r - 有没有办法在 mutate 列中使用表中的查找值?
- python - 如何将多个fasta序列切片为fasta格式范围内长度的子字符串?
- html - 从表格中删除边框并为交替行添加颜色?
- amazon-dynamodb - DynamoDB GSI 如何处理缺失的属性?
- vue.js - 将数据从 PHP/HTML 传递到 .vue 组件
- css - 以恒定速度响应背景滚动
- php - 如何将多维数组转换为单个数组
- c# - Unity 2d PONG 教程在代码部分有令人困惑的提及
- go - 如何使用 GORM 创建 Postgres 数据库