leetcode 206. Reverse Linked List

Reverse a singly linked list.

Example:

Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL

Follow up:

A linked list can be reversed either iteratively or recursively. Could you implement both?

 

解法一:遍历(我的方法)

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode reverseList(ListNode head) {
        if(head == null) return null;
        ListNode res = new ListNode(head.val);
        head = head.next;
        while(head != null){
            ListNode z = res;
            res = new ListNode(head.val);
            res.next = z;
            head = head.next;
        }
        return res;
    }
}

解法二:递归(看不懂。。。)

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 @ 2019-02-02 20:07  JamieLiu  阅读(78)  评论(0编辑  收藏  举报