LeetCode most common 100 questions

foreword

text

1. Reverse linked list

1. Topic

insert image description here

2. Answer

a. Iterative method:

Answer
/**
 * 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. Recursive method:

Answer
/**
 * 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;
    }
};

Summarize

To be updated~

reference

  1. Sword Pointer Offer
  2. Leetcode 100 questions

Guess you like

Origin blog.csdn.net/qq_43211060/article/details/124550313