反转链表 206 Java 4/20
- Reverse Linked List - Easy
地址: https://leetcode.com/problems/reverse-linked-list/
题目描述
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: []
思路
遍历链表, 将当前节点的next指针改为指向前一个节点。 要事先存储当前节点的后一个节点,方便curr指针后移。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
ListNode prev = null;//最后指向null
ListNode curr = head;//从头开始遍历
//遍历直到null
while (curr != null){
//存储节点,
ListNode next = curr.next;
//把当前节点curr的next指针指向前一个
curr.next = prev;
prev = curr;
//
curr = next;
}
return prev;
}
}