迭代法
定义了一个prev 一个cur 一个temp
public ListNode reverseList(ListNode head) {
ListNode prev = null;
ListNode cur = head;
while (cur != null) {
ListNode nextTemp = curr.next;
cur.next = prev;
prev = curr;
cur = nextTemp;
}
return prev;
}
递归法
图片分析来自LeetCode
`
重点就是 head.next.next=head 实际上就是把。head.next转向了。然后将head.next=null.则将head与head.next的链接翻转。
注意终止条件是head.next=null.
class Solution {
public ListNode reverseList(ListNode head) {
if (head.next == null ) return head;
ListNode p = reverseList(head.next);
head.next.next = head;
head.next = null;
return p;
}