反转链表(递归)

 我的方法:迭代

class Solution {
public ListNode reverseList(ListNode head) {
       
       if(head==null) return null;
       if(head.next==null) return head;
       ListNode pos=head.next;
       ListNode pos2=head;
       while(head.next!=null){
           head.next=pos.next;
           pos.next=pos2;
           pos2=pos;
           pos=head.next;
       }
       return pos2;
}
}

第二种方法:递归

public ListNode reverseList(ListNode head) {
    if (head == null || head.next == null) return head;
    ListNode p = reverseList(head.next);
    head.next.next = head;
    head.next = null;
    return p;
}

原文地址:https://www.cnblogs.com/focusonoutput/p/13527159.html