題目來源於 LeetCode 上第 206號(Reverse Linked List)問題,題目難度爲 Easy,AC率55.2%面試
題目地址:https://leetcode.com/problems/reverse-linked-list/算法
Reverse a singly linked list.數組
反轉一個單鏈表bash
Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL
複製代碼
尋找遞歸結束條件:當鏈表只有一個節點,或者若是是空表的話,結束遞歸函數
head == null || head.next == null
複製代碼
調用函數自己,傳入下一個節點post
reverseList(head.next);
複製代碼
咱們把 2->3->4->5 遞歸成了 5->4->3->2, 對於1節點沒有去更改,因此1的next節點指向的是2,以下所示ui
遞歸前:
1 -> 2 -> 3 -> 4 -> 5
遞歸後:
1 -> 2 <- 3 <- 4 <- 5
|
v
null
複製代碼
最後將節點 2 的 next 指向 1,而後把 1 的 next 指向 null,以下所示spa
null <- 1 <- 2 <- 3 <- 4 <- 5
複製代碼
算法效率以下圖所示: 3d
class Solution {
public ListNode reverseList(ListNode head) {
if(head == null || head.next == null) return head;
ListNode nextNode = reverseList(head.next);
ListNode tempNode = head.next;
tempNode.next = head;
head.next = null;
return nextNode;
}
}
複製代碼
設置三個節點 preNode, head, nextcode
算法效率以下圖所示:
class Solution {
public ListNode reverseList(ListNode head) {
ListNode preNode = null;
while (head!=null){
ListNode next = head.next;
head.next = preNode;
preNode = head;
head = next;
}
return preNode;
}
}
複製代碼
算法效率以下圖所示:
class Solution {
public ListNode reverseList(ListNode head) {
ListNode newHead = new ListNode(0);
while (head!=null){
ListNode tempNode = new ListNode(head.val);
tempNode.next = newHead.next;
newHead.next = tempNode;
head = head.next;
}
return newHead.next;
}
}
複製代碼