数据结构-有序链表
N.1 有序链表介绍
|
1)前面的链表实现插入数据都是无序的,在有些应用中需要链表中的数据有序,这称为有序链表。 在有序链表中,数据是按照关键值有序排列的。一般在大多数需要使用有序数组的场合也可以使用有序链表。有序链表优于有序数组的地方是插入的速度(因为元素不需要移动),另外链表可以扩展到全部有效的使用内存,而数组只能局限于一个固定的大小中。 |
————————————————————————

————————————————————————
N.2 有序链表的排序案例
————————————————————————

————————————————————————
|
public class OrderLinkedList { private Node head; private int size;//链表节点的个数 private class Node{ private double data; private Node next; public Node(double data){ this.data = data; } } //插入节点,并按照从小打到的顺序排列,这里的话可以结合图片来开 public void insert(double value){ Node node = new Node(value); Node preTmp = null;//前节点 Node current = head; while(current != null && value > current.data){ preTmp = current; current = current.next;//current指向的地址 赋值给 current } if(preTmp == null){//1 head = node; head.next = current; }else{ preTmp.next = node; node.next = current; } size++; } //显示节点信息 public void display(){ if(size >0){ Node node = head; int tempSize = size; if(tempSize == 1){//当前链表只有一个节点 System.out.println("["+node.data+"]"); return; } while(tempSize>0){ if(node.equals(head)){//判断是否是头节点 System.out.print("["+node.data+"->"); }else if(node.next == null){ System.out.print(node.data+"]"); }else{ System.out.print(node.data+"->"); } node = node.next; tempSize--; } System.out.println(); }else{ //如果链表一个节点都没有,直接打印[] System.out.println("[]"); } } //删除头节点 public void deleteHead(){ head = head.next; size--; } } class test2{ public static void main(String[] args) { OrderLinkedList orderLinkedList=new OrderLinkedList(); orderLinkedList.insert(32.25); orderLinkedList.insert(23.25); orderLinkedList.insert(41.25); orderLinkedList.insert(15.25); System.out.println("链表数据:"); orderLinkedList.display(); System.out.println("删除链头后的数据:"); orderLinkedList.deleteHead(); orderLinkedList.display(); } } /** 链表数据: [15.25->23.25->32.25->41.25] 删除链头后的数据: [23.25->32.25->41.25] */ |
魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐


所有评论(0)