java单链表冒泡排序

去面试的一家公司出的面试题,让我回来做完发过去,记录一下 :arrow:
节点类:

//节点类
class Node{
public Node(int value){
this.value = value;
}
public Node(){
}
int value;
Node next;
}

获得随机的链表

//获得一个随机的单链表
public Node getRandomSingList(){
Node head = new Node();
Node n1 = new Node((int)(Math.random()*100));
Node n2 = new Node((int)(Math.random()*100));
Node n3 = new Node((int)(Math.random()*100));
Node n4 = new Node((int)(Math.random()*100));
Node n5 = new Node((int)(Math.random()*100));
n1.next = n2;
n2.next = n3;
n3.next = n4;
n4.next = n5;
head.next = n1;
return head;
}

打印链表

//打印单链表
public void printList(Node head){
String str = "";
for(Node n = head;n!=null;){
str = str + " " + n.value;
n = n.next;
}
System.out.println(str);
}

冒泡排序

//单链表冒泡排序
public Node blueSortList(Node node){
System.out.println("blue start...");
//当前节点
Node cur = node.next;
//下一个节点
Node next = cur.next;
//前一个节点,两节点n1,n2交换位置时需要前一个节点的next指向n2节点
Node upperNode = node;
//一次排序的最后一个节点
Node lastNode = null;
int i = 1;
//当第二个节点为当次排序的最后一个节点时,整体排序结束
while(node.next != lastNode){
//当下一个节点为一次次排序的最后一个节点时,本次排序结束。
if(next == lastNode){
lastNode = cur;
cur = node.next;
next = cur.next;
upperNode = node;
}else if(next.value < cur.value){
cur.next = next.next;
next.next = cur;
upperNode.next = next;
upperNode = next;
}else{
upperNode = cur;
cur = cur.next;
}
next = cur.next;
System.out.println("第" + i++ + "次排列结果:");
printList(node.next);
}
System.out.println("blue end...");
return node;
}

调用

Test t = new Test();
Node randomList = t.getRandomSingList();
System.out.println("排序前:");
t.printList(randomList.next);
System.out.println("====================");
Node sortList = t.blueSortList(randomList);
System.out.println("====================");
System.out.println("排序后:");
t.printList(sortList.next);
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值