末日搭车指南
面向人生编程

导航

 

 

 我的方法:迭代

 

 

 

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;
}

 

 

posted on 2020-08-19 08:13  末日搭车指南  阅读(147)  评论(0)    收藏  举报