206. 反转链表

给你单链表的头节点 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
cpp 复制代码
/**
 * 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 = NULL;
        ListNode* cur = head;
        while (cur != NULL){
            ListNode* temp = cur->next;
            cur->next = pre;
            pre =cur;
            cur = temp;
        }
        return pre;
    }
};
相关推荐
aloha_7891 小时前
力扣hot100做题整理91-100
数据结构·算法·leetcode
Tiny番茄1 小时前
31.下一个排列
数据结构·python·算法·leetcode
挂科是不可能出现的1 小时前
最长连续序列
数据结构·c++·算法
_Aaron___2 小时前
List.subList() 返回值为什么不能强转成 ArrayList
数据结构·windows·list
码农多耕地呗4 小时前
力扣146.LRU缓存(哈希表缓存.映射+双向链表数据结构手搓.维护使用状况顺序)(java)
数据结构·leetcode·缓存
晚枫~4 小时前
数据结构基石:从线性表到树形世界的探索
数据结构
hadage2334 小时前
--- 数据结构 AVL树 ---
数据结构·算法
liu****4 小时前
8.list的使用
数据结构·c++·算法·list
立志成为大牛的小牛4 小时前
数据结构——二十六、邻接表(王道408)
开发语言·数据结构·c++·学习·程序人生
学编程就要猛6 小时前
数据结构初阶:时间和空间复杂度
数据结构