給一個ListNode,回傳反轉後的結果。
https://leetcode.com/problems/reverse-linked-list/
範例Input: head = [1,2,3,4,5]
Output: [5,4,3,2,1]
操作方式使用遞迴來思考,如下圖,每次都將下一組Node(藍框處)丟入遞迴中迴轉,再把外側的連結反轉即可。
public ListNode reverseList(ListNode head) {
if (head != null && head.next != null) {
//藍框的區塊
ListNode second = head.next;
//將藍框丟入遞迴
ListNode tmp = reverseList(second);
//將外側的指向反轉
second.next = head;
head.next = null;
return tmp;
}
return head;
}

沒有留言:
張貼留言