LeetCode算法入门 反转链表 解法与分析

问题描述:

反转一个单链表。

示例:

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

进阶:
你可以迭代或递归地反转链表。你能否用两种方法解决这道题?

解法一:

扫描一遍,每扫描到一个节点,就将这个节点与下个节点的方向颠倒一下,扫描一遍之后就实现了反转。

代码如下:

/**
 * 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 *current = head;//当前的节点
        ListNode *temp_next;
        ListNode *preview = NULL;//前边的节点
        while(current != NULL){            
            temp_next = current->next;
            current->next=preview;
            preview=current;
            current=temp_next;
        }
        return preview;
    }
};

自己画的原理图如下(太难看了,自己都看不下去了):

解法二:

把上面的代码修改成使用递归的方法。

可以加一个“哑结点”指向头结点。

代码如下:

ListNode* reverseList(ListNode* head) {
        if(!head){
            return nullptr;
        }
        return reverse(head, head, head->next);        
    }
    
    ListNode* reverse(ListNode* head, ListNode* first, ListNode* target){
        if(!target){
            return head;
        }
        first->next = target->next;
        ListNode* temp = target->next;
        target->next = head;
        return reverse(target, first, temp);
    }

这个递归代码参考大佬的:

作者:sunshy
链接:https://leetcode-cn.com/problems/two-sum/solution/die-dai-di-gui-jie-fa-by-sunshy/

解法三:

力扣官方的递归方法:

在这里插入图片描述

代码如下:

/**
 * 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 *p = reverseList(head->next);
    head->next ->next = head;
    head->next = NULL;
    return p;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章