Java实现单链表的排序

来源:互联网 发布:淘宝夜鹰 编辑:程序博客网 时间:2024/06/10 10:31

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

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

与外重循环的节点值进行判断,如果值比外重循环的值小,就交换之。

相当与每次循环把最小的值放到前面。

下面放上代码:

/** * 链表的结构 * @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