我试图成对地反转链表,如下所示
1->2->3->4->5 changed to 2->1->4->3->5
我已经能够递归地做到这一点。但是,我在迭代的时候感到困惑。
public class FastList<Item>
{
private Node<Item> first;
private static class Node<Item>
{
Item item;
Node<Item> next;
}
public void swapPairwiseIterative() // not working
{
if(first == null || first.next==null)
return;
Node one = first, two;
first= first.next;
while ( one != null || one.next != null )
{
two = one.next;
one.next = two.next;
two.next = one;
one = one.next.next;
}
}
}
在调试时,我注意到我能够正确地交换两个节点,但是无法将其分配回first
实例变量,该变量指向列表的第一个元素。我该怎么做?
此外,该行
first= first.next;
看起来有点hacky。请建议一种更自然的方式。
答案 0 :(得分:1)
尝试这样的事情:
public void swapPairwiseIteratively() {
if(first == null || first.next==null) return;
Node one = first, two = first.next, prev = null;
first = two;
while (one != null && two != null) {
// the previous node should point to two
if (prev != null) prev.next = two;
// node one should point to the one after two
one.next = two.next;
// node two should point to one
two.next = one;
// getting ready for next iteration
// one (now the last node) is the prev node
prev = one;
// one is prev's successor
one = prev.next;
// two is prev's successor's successor
if (prev.next != null) two = prev.next.next;
else two = null;
}
}
我不确定你能用两个指针代替三个指针。我会从上面的解决方案(我没有测试它,但它应该是正确的)工作,并弄清楚它是否可以改进。我不认为可以删除行first = two
。
如果移动第一对交换出循环,则可以删除条件if (prev != null)
(此示例中的优化不成熟)。
答案 1 :(得分:1)
您可以递归或非递归地执行此操作。
public void reverseRecursive(Node startNode)
{
Item tmp;
if(startNode==null || startNode.next ==null)
return;
else
{
tmp = startNode.item;
startNode.item = startNode.next.item;
startNode.next.item = tmp;
reverseRecursive(startNode.next.next);
}
}
非递归
public void reverseNonRecursive()
{
Node startNode = head;
Item temp;
while(startNode != null && startNode.next != null)
{
temp = startNode.item;
startNode.item = startNode.next.item;
startNode.next.item= temp;
startNode = startNode.next.next;
}
}