206. 反转链表
作者:互联网
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
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 };
标签:head,ListNode,val,206,反转,nullptr,next,链表 来源: https://www.cnblogs.com/MGFangel/p/16065257.html