题解 | #反转链表# 2种解法:双指针、递归

反转链表

http://www.nowcoder.com/practice/75e878df47f24fdc9dc3e400ec6058ca

双指针

public class Solution {
    public ListNode ReverseList(ListNode head) {
        if (head == null) {
            return null;
        } else {
            ListNode next = null;
            ListNode pre = null;

            while (head != null) {
                next = head.next;
                head.next = pre;
                pre = head;
                head = next;
            }
            return pre;
        }
    }
}

递归

public class Solution {
    public ListNode ReverseList(ListNode head) {
        if (head == null || head.next == null) 
            return head;
        ListNode last = ReverseList(head.next);
        head.next.next = head;
        head.next = null;
        return last;
    }
}
全部评论

相关推荐

06-26 17:24
已编辑
宁波大学 Java
一口洪烧肉:哈哈哈哈哈哈哈哈哈哈哈硬要啊
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
06-30 18:19
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务