leetCode:206 反转链表

206. 反转链表

题目:反转一个单链表。

进阶:
链表可以迭代或递归地反转。你能否两个都实现一遍?

非递归代码:

 1 class Solution {
 2     public ListNode reverseList(ListNode head) {
 3         if(head == null) return null;
 4         ListNode pre = null, nex = null;
 5         while(head != null){
 6             nex = head.next;
 7             head.next = pre;
 8             pre = head;
 9             head = nex;
10         }
11         return pre;
12     }
13 }

递归代码:

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

 

posted @ 2018-03-14 21:08  Amenity_arithmetic  阅读(286)  评论(0编辑  收藏  举报