LeetCode75——Day31

编程入门 行业动态 更新时间:2024-10-12 01:25:30

LeetCode75——Day31

LeetCode75——Day31

文章目录

    • 一、题目
    • 二、题解

一、题目

206. Reverse Linked List

Given the head of a singly linked list, reverse the list, and return the reversed list.

Example 1:

Input: head = [1,2,3,4,5]
Output: [5,4,3,2,1]
Example 2:

Input: head = [1,2]
Output: [2,1]
Example 3:

Input: head = []
Output: []

Constraints:

The number of nodes in the list is the range [0, 5000].
-5000 <= Node.val <= 5000

Follow up: A linked list can be reversed either iteratively or recursively. Could you implement both?

二、题解

/*** 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) {//双指针写法ListNode* pre = nullptr;ListNode* cur = head;while(cur){ListNode* tmp = cur->next;cur->next = pre;pre = cur;cur = tmp;}return pre;}
};

更多推荐

LeetCode75——Day31

本文发布于:2023-11-15 15:33:55,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1602044.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!