diseño de mesa
CREATE TABLE `test` (
`id` bigint NOT NULL COMMENT '主键id',
`name` varchar(50) COLLATE NOT NULL COMMENT '名称',
`next_id` bigint DEFAULT NULL COMMENT '指向下一个节点的主键id',
) ;
复制代码
1. Agregar un nuevo registro
- El parámetro pasa el id de la clave principal del dato anterior, y el next_id del dato se consulta de acuerdo con el id y se registra como A
- Establezca el next_id de los nuevos datos en A y guárdelo,
- Modifique el next_id de los datos anteriores a la identificación de la clave principal de los nuevos datos
o
- El next_id predeterminado es -1 , lo que significa que se trata de datos recién agregados. La clasificación se realiza al final y se omiten los pasos de pasar parámetros y consultar.
(Esto no proporcionará la función de inserción en la posición especificada)
2. Modificar la clasificación
- Paso de parámetros
- Datos movidos, antes de mover, la identificación de los datos anteriores ( C )
- Datos movidos, después de mover, la identificación de los datos anteriores ( A )
- La identificación de los datos que se están moviendo ( D )
- Consulta el next_id de A (indicado como B )
- 查询 D 的 next_id (记为 E )
- 修改 A 的 next_id 为 D 的主键 id
- 修改 D 的 next_id 为 B
- 修改 C 的 next_id 为 E
移动思路如下
3. 删除
- 参数传递前一条数据的id、和要删除数据的id,查询出删除数据的 next_id 记为 A
- 修改前一条数据的 next_id 为 A
- 对要删除的数据执行删除
代码实现
1. 简单对象
@Data
public class Tag {
private Integer id;
private String name;
private Integer nextId;
}
复制代码
2. 对数据按照 nextId 排序
public class Test {
public static void main(String[] args) {
// 添加测试数据
// 这里生成的链表应为:10 -> 40 -> 20 -> 30 -> 50
List<Tag> tags = addData();
// 根据每项数据的nextId建立map
Map<Integer, Tag> map = tags.stream().collect(Collectors.toMap(Tag::getNextId, t -> t));
// -1 默认为最后一项
Tag lastTag = map.get(-1);
LinkedList<Tag> tagLinkedList = new LinkedList<>();
tagLinkedList.addFirst(lastTag)
// 使用递归从map中提取数据
get(lastTag.getId(), map, tagLinkedList);
tagLinkedList.forEach(System.out::println);
}
private static void get(int preId, Map<Integer, Tag> map, LinkedList<Tag> tagList) {
Tag tag = map.get(preId);
if (tag == null) {
return;
}
tagList.addFirst(tag);
get(tag.getId(), map, tagList);
}
private static List<Tag> addData() {
List<Tag> tagList = new ArrayList<>();
Tag tag1 = new Tag();
tag1.setId(10);
tag1.setName("tag1");
tag1.setNextId(40);
tagList.add(tag1);
Tag tag4 = new Tag();
tag4.setId(40);
tag4.setName("tag4");
tag4.setNextId(20);
tagList.add(tag4);
Tag tag2 = new Tag();
tag2.setId(20);
tag2.setName("tag2");
tag2.setNextId(30);
tagList.add(tag2);
Tag tag3 = new Tag();
tag3.setId(30);
tag3.setName("tag3");
tag3.setNextId(50);
tagList.add(tag3);
Tag tag5 = new Tag();
tag5.setId(50);
tag5.setName("tag5");
tag5.setNextId(-1);
tagList.add(tag5);
return tagList;
}
}
复制代码
3. 输出结果
Tag(id=10, name=tag1, nextId=40)
Tag(id=40, name=tag4, nextId=20)
Tag(id=20, name=tag2, nextId=30)
Tag(id=30, name=tag3, nextId=50)
Tag(id=50, name=tag5, nextId=-1)
复制代码