单链表冒泡排序

一. 题目

如题.

代码请到我的代码库中下载 Point2Offer

二. 代码

package week_4;

/**
 * 单链表冒泡排序
 * @author dingding
 * Date :2017-7-3 12:25
 */
public class SortLink {

    public static void main(String[] args) {
        test1();
        test2();
        test3();
        test4();
    }

    //solution,冒泡排序,直接交换两个值,关键在于循环条件
    private static Node Sort(Node head){
        if (head == null) {
            return null;
        }
        if (head.next == null) {
            return head;
        }

        Node tail = null;
        Node cur = null;
        cur = head;
        while(cur != tail){
            while (cur.next != tail){
                if (cur.value>cur.next.value) {
                    int temp = cur.value;
                    cur.value = cur.next.value;
                    cur.next.value = temp;
                }
                cur = cur.next;
            }
            tail = cur;  //不等于最后一个数
            cur = head;  //第二轮head为4
        } 

        return head;
    }

    //打印链表
    private static void printLink(Node head){
        if (head == null) {
            System.out.println("Invalid input.");
            return;
        }
        while (head != null){
            System.out.print(head.value+" ");
            head = head.next;
        }
        System.out.println();
    }

    /*======================测试用例===============*/
    private static void test1() {
        Node first = new Node(5);
        Node second = new Node(4);
        Node third = new Node(3);
        Node fourth = new Node(2);
        Node fifth = new Node(1);

        first.next = second;
        second.next = third;
        third.next = fourth;
        fourth.next = fifth;

        Node head = Sort(first);
        printLink(head);

    }

    private static void test2() {
        Node first = new Node(1);
        Node second = new Node(2);
        Node third = new Node(3);
        Node fourth = new Node(2);
        Node fifth = new Node(6);

        first.next = second;
        second.next = third;
        third.next = fourth;
        fourth.next = fifth;

        Node head = Sort(first);
        printLink(head);        
    }

    private static void test3() {
        Node first = new Node(1);

        Node head = Sort(first);
        printLink(head);                
    }

    private static void test4() {
        Node head = Sort(null);
        printLink(null);                
    }

}

//定义一个链表
class Node{
    int value;
    Node next;
    public Node(int value){
        this.value = value;
        this.next = null;
    }
}


有不妥当之处,麻烦告知:D

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值