经典面试题 反转链表, 采用迭代法,图解超详细
206. 反转链表
https://leetcode.cn/problems/reverse-linked-list/?favorite=2cktkvj


迭代法
思路
用三个指针, 让curr.next不断指向prev,然后不断的后移三个指针,知道curr指向null
图解


就是改变curr.next的指向,从而反转链表(*^▽^*)



结束遍历
完整代码
/**
* 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;
ListNode curr = head;
while(curr != null){
ListNode next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
return prev;
}
}