简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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