firstLast Java Linked list/nodes

Anna :

I'm confused on how each node gets linked to another and how to make sure that if I want the first node to be linked in after the one at the end, I'm not running an infinite loop. For example, in this problem..

Write a method firstLast that could be added to the LinkedIntList class that moves the first element of the list to the back end of the list. Suppose a LinkedIntList variable named list stores the following elements from front (left) to back (right):

[18, 4, 27, 9, 54, 5, 63] If you made the call of list.firstLast();, the list would then store the elements in this order:

[4, 27, 9, 54, 5, 63, 18] If the list is empty or has just one element, its contents should not be modified.

My first attempt is to do this..but to no avail:

`public void firstLast(){
    ListNode temp = front;//stores/references the first node
    temp.next = null;//ensures that first node isn't referring to any other 
//node
    ListNode current = front;//reaches end node/first one with a null 
//reference
    while(current.next != null){
        current = current.next;
    }
    front.next = temp;//links end node to first node
    front = current.next;////now that skips the first element`

but the output is [18] -> [18] (cycles!) . Please advise

janos :

I'm confused on how each node gets linked to another

In a single-linked list, every node knows only the next one. So you need to keep track of the first, commonly called head (in your implementation it's "front"), because it's essential to access all the elements.

... and how to make sure that if I want the first node to be linked in after the one at the end, I'm not running an infinite loop.

The last node has no next node after it, so it's next pointer is null. You can use this condition to avoid infinite loops. (Just make sure the last node has next correctly as null.)

Your implementation could be fixed as:

public void firstLast() {
    // list is empty or has single element -> nothing to do
    if (front == null || front.next == null) {
        return;
    }

    // save the first
    ListNode first = front;

    // move the head
    front = front.next;

    // find the end
    ListNode current = front;
    while (current.next != null) {
        current = current.next;
    }

    // append the node
    current.next = first;

    // reset the next pointer of the new last node
    first.next = null;
}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=460360&siteId=1