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: []
解题思路:
- 申请一个pre指向null
- 遍历节点到null
-
先保存当前节点下一个节点
-
把当前节点的下一节点指向pre
-
把pre指向当前节点
class Solution { public ListNode reverseList(ListNode head) { // corner case if (head == null || head.next == null) { return head; } // normal case ListNode pre = null; while (head != null) { ListNode next = head.next; head.next = pre; pre = head; head = next; } return pre; } }