LeetCode 最常见100道题

前言

正文

一、反转链表

1. 题目

在这里插入图片描述

2. 解答

a. 迭代法:

答案
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
    
    
public:
    ListNode* reverseList(ListNode* head) {
    
    
        if (head==nullptr||head->next==nullptr)
            return head;
        ListNode* node = head;
        ListNode* next = nullptr;
        ListNode* pre = nullptr;
        ListNode* newHead = nullptr;//1. 比较标准的迭代四件套
        while(node)
        {
    
    
            next = node->next;//2. 获取下一个节点
            node->next = pre;//3. 直接先进行反转
            pre = node;//4. 反转后,进行赋值
            node = next;
            if (node == nullptr)//5. 赋值后,进行判断
                newHead = pre;
        }
        return newHead;
    }

};

b. 递归法:

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

        ListNode* result = reverseList(head->next);//1. 想象成只有三个节点,result接下去的就是head->next的所有节点
        head->next->next = head;//2. 将head->next 的next 指向head,这就是所谓的反转操作
        head->next = NULL;  //3. 而这一步则是将所有head->next
        return result;
    }
};

总结

待更~

参考

  1. 剑指Offer
  2. Leetcode 100题

猜你喜欢

转载自blog.csdn.net/qq_43211060/article/details/124550313