这是我到目前为止的方法。我不知道该怎么做。我希望该方法采用一个 int 参数,表示用户想要在链表中反转多少个对象。
public void reverseFirstFew(int howMany) // NOT DONE
{
ListIterator iterator = listIterator();
Object temp = null;
if(howMany <= 0){
throw new IndexOutOfBoundsException();
}
if(howMany > size()){
throw new IndexOutOfBoundsException();
}
}
我还有一个自定义的 ListIterator 类。这是其中的方法。
public ListIterator listIterator()
{
return new LinkedListIterator();
}
private class LinkedListIterator implements ListIterator
{
private Node position;
private Node previous;
// Constructs an iterator that points to the front
// of the linked list. of the linked list.
public LinkedListIterator()
{
position = null;
previous = null;
}
// Moves the iterator past the next element, and returns
// the traversed element's data.
public Object next()
{
if (!hasNext())
throw new NoSuchElementException();
previous = position; // Remember for remove
if (position == null)
position = first;
else
position = position.next;
return position.data;
}
// Tests if there is an element after the iterator position position
public boolean hasNext()
{
if (position == null)
return first != null;
else
return position.next != null;
}
// Adds an element after the iterator position
// and moves the iterator to the inserted element.
public void add(Object element)
{
if (position == null)
{
addFirst(element);
position = first;
}
else
{
Node newNode = new Node();
newNode.data = element;
newNode.next = position.next;
position.next = newNode;
position = newNode;
}
previous = position;
}
// Removes the last traversed element. This method may
// only be called after a call to the next() method.
public void remove()
{
if (previous == position)
throw new IllegalStateException();
if (position == first)
{
removeFirst();
}
else
{
previous.next = position.next;
}
position = previous;
}
// Sets the last traversed element to a different value
public void set(Object element)
{
if (position == null)
throw new NoSuchElementException();
position.data = element;
}
}//end of
如果有人能指导我朝着正确的方向前进,我将不胜感激。
最佳答案
使用 List.subList(int fromIndex, int toIndex)
和 Collections.reverse(List<?> list)
:
Collections.reverse(list.subList(0, howMany));
适用于 ArrayList
和 LinkedList
。例子
List<Integer> list = new LinkedList<>(Arrays.asList(1,2,3,4,5,6,7,8,9));
Collections.reverse(list.subList(0, 4));
System.out.println(list);
输出[4, 3, 2, 1, 5, 6, 7, 8, 9]
至于为什么会这样,引用 subList
的 javadoc :