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 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode() : val(0), next(nullptr) {} 7 * ListNode(int x) : val(x), next(nullptr) {} 8 * ListNode(int x, ListNode *next) : val(x), next(next) {} 9 * }; 10 */ 11 class Solution { 12 public: 13 ListNode* reverseList(ListNode* head) { 14 ListNode *reverse = nullptr; 15 ListNode *next = nullptr; 16 while (head != nullptr) { 17 next = head->next; 18 head->next = reverse; 19 reverse = head; 20 head = next; 21 } 22 return reverse; 23 } 24 };