【问题标题】:What is the right way to sort a linked list in Java?在Java中对链表进行排序的正确方法是什么?
【发布时间】:2016-11-09 20:21:23
【问题描述】:

我有这个链表:

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();
    }
}

我想知道我应该如何对这个链表进行排序?我试图对其进行排序,但奇怪的数字开始出现,在其他情况下,它什么也不做,什么也不排序。

【问题讨论】:

  • 欢迎来到 Stack Overflow!看来您需要学习使用调试器。请帮助自己一些complementary debugging techniques。如果之后仍有问题,请随时回来提供更多详细信息。

标签: java sorting linked-list


【解决方案1】:

您可以在插入时使链表排序。这样您就不需要其他功能来对其进行排序。您没有考虑头部将为空的初始场景,这只是错误

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;
}

【讨论】:

  • 这不是我们想要的......我只想要一个没有插入的排序方法
  • 那么您应该更新问题中的确切要求,以免其他人对您的问题感到困惑
猜你喜欢
  • 2019-06-19
  • 1970-01-01
  • 2010-12-16
  • 2014-04-15
  • 2023-04-03
  • 1970-01-01
  • 1970-01-01
  • 2021-12-04
  • 2015-06-14
相关资源
最近更新 更多