欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

java 有序列表

程序员文章站 2022-06-08 21:46:35
...

package practice.com.wzy.order;

 

/**

 * 有序链表

 *

 */

public class OrderLinkedList {

 

private Node head;

 

private class Node {

private int data;

private Node next;

public Node(int data) {

this.data = data;

}

}

 

public OrderLinkedList() {

head = null;

}

 

//插入节点,并按照从小到大的顺序排列

public void insert(int data) {

Node node = new Node(data);

Node pre = null;

Node current = head;

while(current != null && data > current.data) {

pre = current;

current = current.next;

}

if(pre == null) {

head = node;

head.next = current;

}else {

pre.next = node;

node.next = current;

}

}

 

//删除头部节点

public void deleteHead() {

if(head == null) {

return;

}

head = head.next;

}

 

//显示节点信息

public void display() {

Node current = head;

while(current != null) {

System.out.print(current.data+" ");

current = current.next;

}

System.out.println();

}

 

}

测试:

public class TestOrderLinkedList {

 

@Test

public void testOrderLinkedList() {

OrderLinkedList link = new OrderLinkedList();

link.insert(9);

link.insert(5);

link.insert(7);

link.insert(0);

link.insert(3);

link.insert(10);

link.display();

link.deleteHead();

link.display();

}

 

}

结果:

0 3 5 7 9 10 

3 5 7 9 10 

 

相关标签: 数据结构