206. 反转链表 [Leetcode] 206. 反转链表 java 迭代和递归

 一、迭代(https://blog.csdn.net/fx677588/article/details/72357389 )

class Solution {
    public ListNode reverseList(ListNode head) {
        if(head==null||head.next==null){
            return head;
        }
        ListNode p=null;
        ListNode q=null;
        while(head!=null){
            q=head.next;//把head.next的位置给q
            head.next=p;//把p的位置给head.next
            p=head;//把head的位置给p
            head=q;//把q的位置给head
        }
        return p;
    }
}

二、递归(http://www.cnblogs.com/tengdai/p/9279421.html)

class Solution {
    public ListNode reverseList(ListNode head) {
        if(head==null||head.next==null){
            return head;
        }
        ListNode second=head.next;
        ListNode reverseHead=reverseList(second);
        second.next=head;
        head.next=null;
        return reverseHead;
    }
}

猜你喜欢

转载自blog.csdn.net/niceHou666/article/details/83003130