I need to write a method in Java that moves the first element in a linked list to the last position.
To accomplish this, I believe I'd have to set a node to reference the first element after the head, then set the next node to null. I tried to do this with my method, but when running the method, the output is incorrect.
The rest of the class I have is most likely too large to post here, but I think I only need help on conceptualizing how to move the first element to the end of the list.
The method I have written is:
public void moveFirstToEnd() {
if (head.next == null) {
throw new NoSuchElementException();
}
Node node = head.next;
node.next = null;
head.next = node;
tail.next = node;
tail = node;
}
You want to remove the head of the list and make it the new tail. You should work out how to do that in your head, and the code will be a logical representation of that.
- Remove the head of the list. The new head becomes the next item.
- The removed item stands alone, now; there's nothing after it.
- Place the node at the end of the list. The new tail becomes that node.
Your code now, as you can see, doesn't exactly do that. Working through one step at a time:
So, step 1:
Node node = head;
head = head.next; // <- remove head, new head becomes next item
Then, step 2:
node.next = null; // there's nothing after it.
And finally, step 3:
tail.next = node; // <- add to end of list
tail = node; // <- becomes new end of list
Or, if you'd rather visualize it:
Node node = head:
+------+ +------+ +------+ +------+
| head |--->| |--->| |--->| tail |
+------+ +------+ +------+ +------+
node
head = head.next:
+------+ +------+ +------+ +------+
| |--->| head |--->| |--->| tail |
+------+ +------+ +------+ +------+
node
node.next = null:
+------+ +------+ +------+ +------+
| | | head |--->| |--->| tail |
+------+ +------+ +------+ +------+
node
tail.next = node:
+------+ +------+ +------+ +------+
| head |--->| |--->| tail |--->| |
+------+ +------+ +------+ +------+
node
tail = node:
+------+ +------+ +------+ +------+
| head |--->| |--->| |--->| tail |
+------+ +------+ +------+ +------+
node
By the way, if you already happen to have a popFront
(or whatever) and/or append
operation defined, don't forget you can use those, too; no sense duplicating code:
Node node = popFront(); // if you have this
append(node); // if you have this
You can do:
public void moveFirstToLast(LinkedList<E> list){
if(list.size() < 2)
return;
E aux = list.get(0);
list.remove(0);
list.add(list.size(),aux);
}
You can do:
LinkedList<E> list = new LinkedList<E>();
list.addLast(list.pop());