简体   繁体   English

如何在向后构建的单链接列表中交换两个节点?

[英]How do I swap two nodes in a singly linked list built backwards?

I've been messing with this for a while now and it seems like no matter what I do my output is always truncated or "sorted" arbitrarily. 我已经搞混了一段时间了,看来无论我做什么,我的输出总是被截断或任意“排序”。 Is moving the references around enough to swap the two elements? 是否足够移动引用以交换两个元素? I'm trying to make it so that, if the current node's SSN field is larger than the previous one, link the previous one to the current one. 我试图这样做,以便如果当前节点的SSN字段大于上一个,则将前一个链接到当前字段。 This is how my code looks at the moment: 这是我的代码目前的样子:

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

You likely need something like this 您可能需要这样的东西

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM