实现
- 首先保证插入前的链表是个完整的,最后一个节点要断开
- 然后在插入前链表中找到比待插入节点大的最小元素,插到前面即可
Link.java
class Link {
private class Node {
int data;
Node next;
public Node(int x) {
data = x;
}
public void addNode(Node newNode){
if(this.next == null){
this.next = newNode;
}else{
this.next.addNode(newNode);
}
}
}
public Node root;
public void add(int data){
Node newNode = new Node(data);
if(this.root==null){
this.root=newNode;
}else{
this.root.addNode(newNode);
}
}
public void printLink(){
Node head = this.root;
while(head!=null) {
System.out.println(head.data);
head = head.next;
}
}
public void insertionSortList() {
Node head = this.root;
if(head==null || head.next==null)
return;
Node dummy = new Node(-1);
dummy.next = head;
Node cur = head.next;
head.next = null;
while(cur != null) {
Node pre = dummy;
Node temp = cur.next;
while (pre.next!=null && cur.data > pre.next.data){
pre = pre.next;
}
cur.next = pre.next;
pre.next = cur;
cur = temp;
}
this.root=dummy.next;
return;
}
}
main.java
import java.lang.reflect.Array;
public class Main {
public static void main(String[] args) {
Link all = new Link();
int data[] = new int[]{5,4,3,2,1};
// for(int i = 0;i < data.length;i++){
// data[i] = i;
// }
// data[0] = 0;
// int j = data.length-1;
// for(int i = 1;i < data.length;i++){
// data[i] = j;
// j--;
// }
// int j = data.length;
// for(int i = 0;i < data.length;i++){
// data[i] = j;
// j--;
// }
for(int i = 0;i < data.length;i++){
System.out.println(data[i]);
}
for(int i = 0;i < data.length;i++){
all.add(data[i]);
}
long startTime=System.currentTimeMillis();
all.insertionSortList();
long endTime=System.currentTimeMillis();
System.out.println(endTime-startTime);
System.out.println("==================");
all.printLink();
}
}
数据结构分析
- 倒序链表:3->2->1
data | next | |||
R1 | R2 | |||
A | 3 | B | null | |
B | 2 | C | A | |
C | 1 | |||
S | -1 | A |
- 顺序链表:1->2->3
1 | ||||
3 | null | |||
- 乱序链表:3->2->4
C | ||||
4 | ||||
B | B |
变量分析
- 共需定义5个变量:head、dummy、cur、pre、temp,可分为两类
- head、dummy、cur为初始变量,即为了操作链表初始创建的变量,head是链表头节点,dummy是哑节点,用于操作头节点,cur为当前节点,为头节点的下一个节点
- pre、temp为循环变量,是为了在循环中的操作创建,pre从哑节点开始,每次循环后移,比较每个元素和cur的大小,到cur的前一节点为止,temp是cur的下一个节点,用于在循环中将cur后移