赞
踩
有序链表是在单链表的基础上对单链表的表头节点插入进行修改,从表头开始根据插入值与链表中原先存在的数据节点进行比较判断,若大于(或小于)该节点就向后移一个节点进行比较,直至不大于(或小于)该节点,最终实现按照从小到大(或从大到小)的顺序排列链表。
- // 插入节点,并按照从小到大的顺序排列
- public void insert(int value) {
- Node node = new Node(value);
- Node previous = null;
- Node current = head;
- while (current != null && value > current.data) {
- previous = current;
- current = current.next;
- }
- if (previous == null) {
- head = node;
- head.next = current;
- } else {
- previous.next = node;
- node.next = current;
- }
- }
- // 插入节点,并按照从大到小的顺序排列
- public void insert(int value) {
- Node node = new Node(value);
- Node previous = null;
- Node current = head;
- while (current != null && value < current.data) {
- previous = current;
- current = current.next;
- }
- if (previous == null) {
- head = node;
- head.next = current;
- } else {
- previous.next = node;
- node.next = current;
- }
- }

另外,相对于有序数组,链表的插入的速度比较快(因为元素不需要移动),同时链表可以扩展到全部有效的使用内存,而数组则只能固定大小。
在有序链表中插入和删除某一项最多需要O(N)次比较,平均需要O(N/2)次,因为必须沿着链表上一步一步走才能找到正确的插入位置,然而有序链表可以最快速度删除最小值或最大值,因为只需要删除表头即可,如果一个应用需要频繁的存取最值,且不需要快速的插入,那么有序链表是一个比较好的选择方案。比如优先级队列可以使用有序链表来实现。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。