如何交换反向构建的单链表中的两个节点?



我已经弄乱这个有一段时间了,似乎无论我做什么,我的输出总是被截断或任意"排序"。移动引用是否足以交换两个元素?我试图这样做,如果当前节点的SSN字段大于前一个,则将前一个链接到当前节点。这是我的代码现在的样子:

public void loadRecords() throws FileNotFoundException {
    Node head = null;
    Node prev = null;
    Node curr = null;
    Scanner fileRead = makeAFile(database);
    fileRead.useDelimiter(";|n");
    boolean sorted = false;
    while (fileRead.hasNext()) {
        head = new Node(fileRead.next(), fileRead.next(), fileRead.next());
        head.nextOne = prev;
        if (prev != null) {
            for (curr = head; curr != null; curr = curr.nextOne) {
                if ((curr).compareTo(prev) > 0) {
                    head.nextOne = prev.nextOne; //oops, there we go. used to be "head.nextOne = curr.nextOne".
                    prev = head; // not even sure if this is what I want
                    sorted = true;
                } else
                    break;
            }
        }
        if (sorted != true) {
            prev = head;
        }
        sorted = false;
    }
}

您可能需要这样的内容

                Node tmp = head.nextOne
                head.nextOne = prev.nextOne;
                prev.nextOne = tmp;

相关内容

  • 没有找到相关文章

最新更新