我试图用“仅”两个指针递归地反向链接列表。实际上,每个递归调用都会临时创建第三个指针来辅助它。我有一种特定的算法,试图在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]