codeTop
题目链接
//方法一:
public ListNode reverseList(ListNode head) {
ListNode pre = null;
while (head != null) {
ListNode nex = head.next;
head.next = pre;
pre = head;
head = nex;
}
return pre;
}
//方法二:
private ListNode res;
public ListNode reverseList2(ListNode head) {
reverse(head);
return res;
}
public ListNode reverse(ListNode head) {
if (head == null || head.next == null) {
res = head;
return head;
}
ListNode cur = reverse(head.next);
cur.next = head;
head.next = null;
return head;
}
//方法三:
public ListNode reverseList3(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode ans = reverseList3(head.next);
head.next.next = head;
head.next = null;
return ans;
}
static class ListNode {
ListNode next;
}