通过在前面重新启动 Node2 并在每次我认为交换可能有效时将其带到一个较小的索引。
输入为 J I O L输出为 L J I O
public static void swap(Node one, Node two) {
String temp1, temp2;
temp1 = one.getData();
temp2 = two.getData();
two.setData(temp1);
one.setData(temp2);
}
public static void reverse(LinkedList list) {
int index = 0;
Node curr1 = list.getFront();
Node curr2= list.getFront();
for (int i = 0; i <= list.size() / 2; i++) {
for (int j = 0; j <= list.size() - index; j++) {
curr2 = curr2.getNext();
index++;
}
swap(curr1, curr2);
curr1 = curr1.getNext();
}
}
任何帮助将不胜感激
对于您要实现的目标,此功能似乎也非常复杂。如果您想要实现的只是反转列表,请使用这个。
Collections.reverse(list);
输出为 L J I O"
如果你想要这个,你可以选择:
list.add(0,list.removeLast());
根据你的代码,你正在使用你自己的LinkedList实现,所以我假设,无论出于何种原因,你都想自己实现它。
如果是这样,请使用以下代码:
public void ReverseLinkedList (LinkedList linkedList)
{
LinkedListNode start = linkedList.Head;
LinkedListNode temp = null;
// ------------------------------------------------------------
// Loop through until null node (next node of the latest node) is found
// ------------------------------------------------------------
while (start != null)
{
// ------------------------------------------------------------
// Swap the “Next” and “Previous” node properties
// ------------------------------------------------------------
temp = start.Next;
start.Next = start.Previous;
start.Previous = temp;
// ------------------------------------------------------------
// Head property needs to point to the latest node
// ------------------------------------------------------------
if (start.Previous == null)
{
linkedList.Head = start;
}
// ------------------------------------------------------------
// Move on to the next node (since we just swapped
// “Next” and “Previous”
// “Next” is actually the “Previous”
// ------------------------------------------------------------
start = start.Previous;
}
// ------------------------------------------------------------
// That's it!
// ------------------------------------------------------------
}
我从 http://www.codeproject.com/Articles/27742/How-To-Reverse-a-Linked-List-Different-Ways 那里得到的.他们甚至展示了解决此问题的其他 2 种方法。
在其他情况下,我真诚地建议您使用 java.utils.Collections.reverse() :)