206_反转链表
时间:2021-08-30 06:17:05
收藏:0
阅读:7
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;
}
}
原文:https://www.cnblogs.com/iwyc/p/15196399.html
评论(0)