递归地反转只有两个指针的链表会返回吗?

我试图用“仅”两个指针递归地反向链接列表。实际上,每个递归调用都会临时创建第三个指针来辅助它。我有一种特定的算法,试图在this之后使用。在堆栈上运行时,该程序运行良好,但在堆栈上运行时,我的退货似乎无济于事:

public static void main(String[] args)
   {
      ListNode head = new ListNode("hello",null);
      head = new ListNode("foo",head);
      head = new ListNode("boo",head);
      head = new ListNode("nonsense",head);
      head = new ListNode("computer",new ListNode("science",new ListNode("java",new ListNode("coffee",head))));
//head is [computer,science,java,coffee,nonsense,boo,foo,hello]

System.out.print("recur with 2 pointers: \t\t\t\t");
      head = recurTwoPointers(null,head);
      print(head);
public static ListNode recurTwoPointers(ListNode prev,ListNode head)
   {
      if(head == null){
         return head;
      }
      ListNode next = head.getNext();
      head.setNext(prev);
      recurTwoPointers(head,next);
      return next;
   }

我已经尝试过可以想到的所有回报组合。程序进入堆栈,似乎撤消了已完成的操作,并且值丢失了。最后,我最终只返回了

[science,computer]

代替

[hello,computer]
leon_hit 回答:递归地反转只有两个指针的链表会返回吗?

要反转长度为N的列表:

如果N = 1,则返回未修改的列表。

否则,删除并保存列表中的第一项,然后反转长度为N-1的其余列表。将保存的元素添加到末尾后,返回反向列表。

本文链接:https://www.f2er.com/3087665.html

大家都在问