码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode 206. Reverse Linked List

时间:2019-02-02 20:36:53      阅读:159      评论:0      收藏:0      [点我收藏+]

标签:eve   style   col   bsp   递归   div   pre   amp   code   

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

 

leetcode 206. Reverse Linked List

标签:eve   style   col   bsp   递归   div   pre   amp   code   

原文地址:https://www.cnblogs.com/jamieliu/p/10349077.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!