又又学到了捏 (得吃了!)
思路:1.迭代法 2递归
1.迭代法:
public class Solution {
public ListNode reverseList(ListNode head) {
if (head == null) return head;
ListNode now = head, pre = null;
while (now != null) {
ListNode next = now.next;
now.next = pre;
pre = now;
now = next;
}
return pre;
}
}
2:递归
class Solution {
public ListNode reverseList(ListNode head) {
if (head == null || head.next == null) return head;
ListNode newHead = reverseList(head.next);
head.next.next = head;
head.next = null;
return newHead;
}
}
over~