在Java中对链表进行排序的正确方法是什么?

时间:2016-11-09 20:21:23

标签: java sorting linked-list

我有这个链表:

class Node {
    Node next;
    int num;

    public Node(int val) {
        num = val;
        next = null;
    }
}

public class LinkedList {

    Node head;

    public LinkedList(int val) {
        head = new Node(val);
    }

    public void append(int val) {
        Node tmpNode = head;
        while (tmpNode.next != null) {
            tmpNode = tmpNode.next;
        }
        tmpNode.next = new Node(val);
    }
    public void print() {
        Node tmpNode = head;
        while (tmpNode != null) {
            System.out.print(tmpNode.num + " -> ");
            tmpNode = tmpNode.next;
        }
        System.out.print("null");
    }

    public static void main(String[] args) {
        LinkedList myList = new LinkedList(8);
        myList.append(7);
        myList.append(16);
        myList.print();
    }
}

我想知道如何对此链表进行排序?我试图对它进行排序,但奇怪的数字开始出现,而在其他情况下,它什么都不做,什么都没有。

1 个答案:

答案 0 :(得分:0)

您可以在插入自身时对链表进行排序。这样你就不需要另外一个函数来对它进行排序。您没有考虑头部仅为空的初始场景,即错误

public void insert(int val) {
Node currentNode = head;
Node nextNode = head.next;

if (head==null) {
    head = new Node(val);
    head.next = null;
    return;
}

if (currentNode.num > val) {
    Node tmpNode = head;
    head = new Node(val);
    head.next = tmpNode;
    return;
}

if (nextNode != null && nextNode.num > val) {
    currentNode.next = new Node(val);
    currentNode.next.next = nextNode;
    return;
}

while (nextNode != null && nextNode.num < val) {
    currentNode = nextNode;
    nextNode = nextNode.next;
}

currentNode.next = new Node(val);
currentNode.next.next = nextNode;
}