firstLast Java Linked list/nodes

Viewed 1616

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

3 Answers
Related