public class LinkedIntListSolution { private ListNode front; private int size; public void moveSecondLastToFront() { if (this.front != null && this.front.next != null && this.front.next.next != null) { ListNode thirdToLast = this.front; while (thirdToLast.next.next.next != null) { thirdToLast = thirdToLast.next; } ListNode secondToLast = thirdToLast.next; thirdToLast.next = secondToLast.next; secondToLast.next = this.front; this.front = secondToLast; } } /** Creates a new empty LinkedIntList */ public LinkedIntListSolution() { this.front = null; } /** Constructs a String representation of the LinkedIntList. * For example, "[1, 2, 3]". */ public String toString() { String result = "["; ListNode current = this.front; // Process all but the last element of the LinkedList while (current != null && current.next != null) { result += current.data + ", "; current = current.next; } // Process the last element (if one exists) if (current != null) { result += current.data; } return result + "]"; } /** Appends value to the end of the LinkedIntList. */ public void add(int value) { if (this.front == null) { this.front = new ListNode(value); } else { ListNode current = this.front; while (current.next != null) { current = current.next; } current.next = new ListNode(value); } this.size++; } /** Returns the size of the LinkedIntList */ public int size() { return this.size; } /** Returns the data at index. * pre: 0 <= index <= size, otherwise throws IllegalArgumentException */ public int get(int index) { checkIndex(index); ListNode current = this.front; for (int i = 0; i < index; i++) { current = current.next; } return current.data; } /** Sets the data at index to value. * pre: 0 <= index <= size, otherwise throws IllegalArgumentException */ public void set(int index, int value) { checkIndex(index); ListNode current = this.front; for (int i = 0; i < index; i++) { current = current.next; } current.data = value; } /** Checks that index is within valid bounds * for the LinkedIntList. * pre: 0 <= index <= size, otherwise throws IllegalArgumentException */ private void checkIndex(int index) { if (index < 0 || index >= this.size) { throw new IllegalArgumentException(); } } /** * ListNode is a class for storing a single node of a linked list that stores * int values. It stores an integer value and a link to the next node of the * linked list. * * @author Adam Blank */ private class ListNode { public int data; public ListNode next; /** Creates a terminal ListNode with 0 as its data. */ public ListNode() { this(0, null); } /** Creates a terminal ListNode with data as its data. */ public ListNode(int data) { this(data, null); } /** Creates a ListNode with data as its data that points to next */ public ListNode(int data, ListNode next) { this.data = data; this.next = next; } } }