下面会有对 链表 的对象的初始化以及数据存入,对链表里的数据进行直接插入排序法排序:
Node 类:
package lianbiao;
public class Node {
//链表节点的数据
int data;
//链表指向的下一个节点的指针
Node next = null;
public Node(int data) {
this.data = data;
}
}
ListNode 类:
package lianbiao;
public class ListNode {
private static int i=1;
public static Node getSingleList(){
//向节点中添加元素
Node head=new Node(8);
Node node1=new Node(7);
Node node2=new Node(6);
Node node3=new Node(5);
Node node4=new Node(4);
Node node5=new Node(3);
Node node6=new Node(2);
Node node7=new Node(1);
//指针指向下一个元素
head.next=node1;
node1.next=node2;
node2.next=node3;
node3.next=node4;
node4.next=node5;
node5.next=node6;
node6.next=node7;
node7.next=null;
return head;
}
public static void printList(Node node){
if (i==1) {
System.out.print("单链表排序前:");
while(node!=null){
System.out.print(node.data+"-->");
node=node.next;
}
System.out.println();
}else {
System.out.print("单链表排序后:");
while(node!=null){
System.out.print(node.data+"-->");
node=node.next;
}
System.out.println();
}
i++;
}
}
SortList 类:
package lianbiao;
public class SortList {
public static void main(String[] args) {
Node head=ListNode.getSingleList(); //得到链表
ListNode.printList(head); //输出排序之前的链表
head=insertSortList(head); //排序链表
ListNode.printList(head); //输出排序完的链表
}
public static Node insertSortList(Node head) {
if(head==null||head.next==null) return head;
Node pre = head;//pre指向已经有序的节点
Node cur = head.next;//cur指向待排序的节点
Node aux = new Node(-1);//辅助节点
aux.next = head;
while(cur!=null){
if(cur.data<pre.data){
//先把cur节点从当前链表中删除,然后再把cur节点插入到合适位置
pre.next = cur.next;
//从前往后找到l2.val>cur.val,然后把cur节点插入到l1和l2之间
Node l1 = aux;
Node l2 = aux.next;
while(cur.data>l2.data){
l1 = l2;
l2 = l2.next;
}
//把cur节点插入到l1和l2之间
l1.next = cur;
cur.next = l2;//插入合适位置
cur = pre.next;//指向下一个待处理节点
}else{// 如果下一个节点 大于等于当前节点,那么 取消判断, 介殿伟后羿。
pre = cur;
cur = cur.next;
}
}
return aux.next;
}
}