递归写法
复习的时候又想了半天
想明白 最后递归返回链表的尾 作为反转链表的头。
当前函数中 head.next还是指正常顺序的下一个, 因此要head.next.next = head进行反转。
不要忘了加head.next=null
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
public ListNode ReverseList(ListNode head) {
if(head == null || head.next == null){
return head;
}
ListNode res = ReverseList(head.next);
head.next.next = head;
head.next = null;
return res;
}
}public class Solution {
public ListNode ReverseList(ListNode head) {
ListNode prev = null;
ListNode cur = head;
while(cur!=null){
ListNode temp = cur.next;
cur.next = prev;
prev = cur;
cur = temp;
}
return prev;
}
}


京公网安备 11010502036488号