19.反转链表
206. 反转链表
给你单链表的头节点head
,请你反转链表,并返回反转后的链表。
示例 1:
![](https://assets.leetcode.com/uploads/2021/02/19/rev1ex1.jpg)
输入:head = [1,2,3,4,5] 输出:[5,4,3,2,1]
示例 2:
![](https://assets.leetcode.com/uploads/2021/02/19/rev1ex2.jpg)
输入:head = [1,2] 输出:[2,1]
示例 3:
输入:head = [] 输出:[]
提示:
- 链表中节点的数目范围是
[0, 5000]
-5000 <= Node.val <= 5000
1 /** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode() {} 7 * ListNode(int val) { this.val = val; } 8 * ListNode(int val, ListNode next) { this.val = val; this.next = next; } 9 * } 10 */ 11 class Solution { 12 public ListNode reverseList(ListNode head) { 13 14 ListNode pre = null; 15 ListNode cur = head; 16 17 while (cur != null){ 18 // 本质是一个暂存下一个数据的temp变量 19 ListNode next = cur.next;
// 将链表反转,将cur指向pre 20 cur.next = pre;
// 继续反转,往pre中存入cur 21 pre = cur;
// 使用最开始的next,保证下一轮能继续进行(所以1,4是保证反转操作继续进行;2,3是用来反转) 22 cur = next; 23 } 24 25 return pre; 26 } 27 }