zoukankan      html  css  js  c++  java
  • 刷题-力扣-206. 反转链表

    206. 反转链表

    题目链接

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/reverse-linked-list/
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

    题目描述

    给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。

    示例 1:

    输入:head = [1,2,3,4,5]
    输出:[5,4,3,2,1]
    

    示例 2:

    输入:head = [1,2]
    输出:[2,1]
    

    示例 3:

    输入:head = []
    输出:[]
    

    提示:

    • 链表中节点的数目范围是 [0, 5000]
    • -5000 <= Node.val <= 5000

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

    题目分析

    1. 根据题目描述反转链表
    2. 使用三个指针front,mid,rear,分别指向前三个结点
    3. mid指向的结点的next指向front指向的结点,再让三个指针在逻辑上向后移动一位

    代码

    /**
     * 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 || !(head->next)) return head;
            ListNode* front = head;
            ListNode* mid = front->next;
            ListNode* rear = mid->next;
            head->next = nullptr;
            while (rear) {
                mid->next = front;
                front = mid;
                mid = rear;
                rear = mid->next;
            }
            mid->next = front;
            return mid;
        }
    };
    
  • 相关阅读:
    CodeForces 697B Barnicle 模拟
    15.三数之和
    167.两数之和
    209.长度最小子数组-sliding window
    COMP9313 Week9a-0
    树总纲(To be continued)
    COMP9517 Week8
    COMP9313 week8b Pipeline
    94. 二叉树的中序遍历
    COMP9313 Week8 Classification and PySpark MLlib
  • 原文地址:https://www.cnblogs.com/HanYG/p/14860338.html
Copyright © 2011-2022 走看看