劍指Offer24-反轉鏈表

劍指Offer典型題整理 - 爭取做最好的題解

劍指Offer24-反轉鏈表

整理時間:2020年02月17日

本題和 LeetCode-206 相同

題目描述

定義一個函數,輸入一個鏈表的頭節點,反轉該鏈表並輸出反轉後鏈表的頭節點,使用遞歸和迭代兩種方式實現。

示例

輸入: 1->2->3->4->5->NULL
輸出: 5->4->3->2->1->NULL

限制:

0 <= 節點個數 <= 5000

題解

這是一道非常經典的題目了,遞歸和迭代兩種實現實現方法更是能夠體現基本編程素養。

😊解法1:雙指針迭代法

需要使用到兩個指針,指針cur定位原先鏈表的頭,指針pre定位逆轉鏈表的頭。解決這種問題最好的方法還是畫圖自己分析,流程圖如下:

在這裏插入圖片描述
C++版本

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        ListNode *pre = NULL;
        ListNode *cur = head;
        while (cur != NULL) {
            ListNode *temp = cur->next;
            cur->next = pre;
            pre = cur;
            cur = temp;
        }
        return pre;
    }
};

python版本

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def reverseList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        pre, cur = None, head
        while cur:
            pre, cur.next, cur = cur, pre, cur.next
        return pre

😐 解法2:遞歸解法

這道題用遞歸求解還是比較繞的,很容易繞暈,我總結的經驗如下:

  1. 找整個遞歸的終止條件:何時終止遞歸?
  2. 找返回值:應該給上一層遞歸返回什麼信息?
  3. 本層遞歸應該做什麼:在這一層遞歸中應該完成哪些內容?

在這個題目中逐一分析:

  1. 終止條件即當前節點爲鏈表的最後一個節點head.next == None或者鏈表本身爲空head == None

    if head == None or head.next == None:
        return head
    
  2. 因爲我們需要最後一個節點作爲返回值,所以應該返回原鏈表最後一個節點(最後一個入棧的節點,即1中返回的節點):

    return ret
    
  3. 在當前遞歸中應該將當前層next節點的next指針指向當前層節點;另外爲了避免鏈表最終成環,需要將當前層的節點的next置爲空:

    head.next.next = head
    head.next = None
    

圖解:

在這裏插入圖片描述

C++版本

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        if (head == NULL || head->next == NULL) {
            return head;
        }
        ListNode *ret = reverseList(head->next);
        head->next->next = head;
        head->next = NULL;
        return ret;
    }
};

python版本

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def reverseList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if head == None or head.next == None:
            return head
        ret = self.reverseList(head.next)
        head.next.next = head
        head.next = None
        return ret

在這裏插入圖片描述

(完)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章