題目
反轉一個單鏈表。
示例:
輸入: 1->2->3->4->5->NULL
輸出: 5->4->3->2->1->NULL
進階:
你可以迭代或遞歸地反轉鏈表。你能否用兩種方法解決這道題?
解法1:迭代法
-
解題思路
迭代法的解題思路並不複雜,遍歷鏈表,將 next 節點取出,使之成爲頭節點,以此循環,知道 next 節點爲 null。
這種反轉鏈表的運用在很多題目中都會用到,比如判斷是否迴文鏈表時,將鏈表的前半部分反轉,判斷是否和鏈表的後半部分相等。 -
代碼
class Solution {
public ListNode reverseList(ListNode head) {
// new node
ListNode nn = null;
// new link
ListNode nl = null;
while (head != null) {
// 保存下一個節點
nn = head.next;
// 當前頭節點成爲新的反轉鏈表的頭節點
head.next = nl;
// 更新反轉鏈表
nl = head;
// 頭節點指向下一節點
head = nn;
}
return nl;
}
}
解法2:遞歸法
- 解題思路
遞歸法的思路不是很好理解,因此我畫了一張圖說明每個語句執行後 newHead 的變化。建議大家可以自己 Debug 看看。
- 代碼
class Solution {
public static ListNode reverseList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode newHead = reverseList(head.next);
// 成環了,因爲newHead和head其實是同一個引用,所以head改變時,newHead也會受到影響
// 此時newHead爲反轉後的鏈表,並且跟着一個鏈表環
head.next.next = head;
// 將環斷開,此時newHead爲反轉後的鏈表
head.next = null;
return newHead;
}
}