插入排序 链表 java_[算法] 单链表插入排序(java)

本文介绍了如何使用Java实现单链表的插入排序。通过创建Link类来操作链表,包括添加节点、打印链表和插入排序。插入排序过程中,创建哑节点dummy辅助操作,遍历链表找到合适位置插入节点,保证链表有序。最后,文章还分析了数据结构和所需变量。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

实现

首先保证插入前的链表是个完整的,最后一个节点要断开

然后在插入前链表中找到比待插入节点大的最小元素,插到前面即可

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

null

B

2

C

A

A

C

1

null

B

S

-1

A

B

C

顺序链表:1->2->3

data

next

R1

R2

A

1

B

B

B

B

2

C

C

C

C

3

null

null

null

S

-1

A

A

A

乱序链表:3->2->4

data

next

R1

R2

A

3

B

null

C

B

2

C

A

A

C

4

null

null

S

-1

A

B

B

变量分析

共需定义5个变量:head、dummy、cur、pre、temp,可分为两类

head、dummy、cur为初始变量,即为了操作链表初始创建的变量,head是链表头节点,dummy是哑节点,用于操作头节点,cur为当前节点,为头节点的下一个节点

pre、temp为循环变量,是为了在循环中的操作创建,pre从哑节点开始,每次循环后移,比较每个元素和cur的大小,到cur的前一节点为止,temp是cur的下一个节点,用于在循环中将cur后移

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值