Problem:
输入一个链表,反转链表后,输出新链表的表头。
Intuition:
我们要用递归的思路完成这个问题,那么第一个节点原来应该指向的是第二个节点,现在指向的是null.对于第n个节点来说,原来指向的应该是第n+1个节点,现在应该指向的是第n-1个节点.那么这个递归关系如何进行构建?实际上问题就变成了我知道如何变换一个长度为n-1的反向链表(利用递归的特性),如何在它前面加一个节点然后拼起来的问题。想象一下从n-1个节点到n个节点的拼装的过程,问题就明确了。
Solution:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
| public class CodingInterview_024 { public class ListNode { int val; ListNode next;
public ListNode(int x){ val=x; } }
public ListNode ReverseListWithRecursion(ListNode head) { if (head == null || head.next == null) return head; ListNode next = head.next; head.next = null; ListNode newHead = ReverseListWithRecursion(next); next.next = head; return newHead; }
public ListNode ReverseListWithLoop(ListNode head) {
if(head==null) return null; ListNode pre = null; ListNode next = null; while(head!=null){ next = head.next; head.next = pre; pre = head; head = next; } return pre; } }
|