对于考试,我训练将一些算法写到期末考试。其中之一是创建reverse()方法,该方法将List <>反向。我的方法两次打印列表的问题。如何更改方法?
这里是List.java文件的代码。方法removeFromBack(),removeFromFront(),insertAtBack(),insertAtFront(),print(),isEmpty(),List和ListNode类已在Deitel的Java书中定义:
public void reverse()
{
if ( isEmpty() )
{
return;
} // end if
ListNode< T > current = firstNode;
// while not at end of list
while ( current != null)
{
insertAtFront(current.data);
current = current.nextNode;
} // end while
}
public void reverse() {
int size = 0;
if (isEmpty()) {
return;
} // end if
ListNode < T > current = firstNode;
while (current != null) {
current = current.nextNode;
size++;
}
current = firstNode;
// while not at end of list
while (size != 0) {
insertAtFront(current.data);
current.data = null;
current = current.nextNode;
size--;
}
current = firstNode;
while (lastNode.data == null) {
removeFromBack();
}
}