Java实现单链表的排序

要想实现链表的排序,使用双重循环,类似于选择排序。

外重循环从头结点循环到尾节点,内重循环从外重循环的节点循环到尾节点,内重循环每个节点的值

与外重循环的节点值进行判断,如果值比外重循环的值小,就交换之。
相当与每次循环把最小的值放到前面。

下面放上代码:


/**
 * 链表的结构
 * @author haoge
 */
public class Node {
    //链表节点的数据
    int data;

    //链表指向的下一个节点的指针
    Node next = null;

    public Node(int data) {
        this.data = data;
    }
}

/**
 * 排序链表
 * @author haoge
 */
public class SortNodeList {

    /**
     * 对链表进行排序:从小到大
     * @param head
     * @return
     */
    public Node sortList(Node head) {
        //记录每次循环的最小值
        int temp ;
        Node curNode = head;
        while (curNode != null) {
            /**
             * 内重循环从当前节点的下一个节点循环到尾节点,
             * 找到和外重循环的值比较最小的那个,然后与外重循环进行交换
             */
            Node nextNode = curNode.next;
            while (nextNode != null) {
                //比外重循环的小值放到前面
                if (nextNode.data < curNode.data) {
                    temp = nextNode.data;
                    nextNode.data = curNode.data;
                    curNode.data = temp;
                }
                nextNode = nextNode.next;
            }
            curNode = curNode.next;
        }
        return head;
    }

    /**
     * 新增节点
     * @param data
     */
    public Node insertNode(int data, Node head) {
        Node node = new Node(data);
        if (head == null) {
            head = node;
            return head;
        }
        Node curNode = head;
        //循环找到当前链表的尾节点
        while (curNode.next != null) {
            curNode = curNode.next;
        }
        //尾节点的指针指向新增加的节点
        curNode.next = node;
        return head;
    }

    /**
     * 打印链表
     */
    public void printList(Node head) {
        Node curNode = head;
        //循环遍历到尾节点
        while (curNode != null) {
            System.out.print(curNode.data + "  ");
            curNode = curNode.next;
        }
        System.out.println();
    }

    public static void main(String[] args) {
        SortNodeList sortNode = new SortNodeList();

        //链表的头指针
        Node head = null;

        //新增节点,第一次新增时需要返回头指针,用于定位链表
        head = sortNode.insertNode(2, head);
        sortNode.insertNode(5, head);
        sortNode.insertNode(4, head);
        sortNode.insertNode(3, head);
        sortNode.insertNode(1, head);

        System.out.println("排序链表前:");
        sortNode.printList(head);

        //排序链表
        head = sortNode.sortList(head);

        System.out.println("排序链表后:");
        sortNode.printList(head);
    }
}

输出结果:

排序链表前:
2  5  4  3  1  
排序链表后:
1  2  3  4  5  
  • 5
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 7
    评论
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值