题解 | #反转链表# 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;
    }
}
全部评论

相关推荐

05-09 14:45
门头沟学院 Java
点赞 评论 收藏
分享
这一集 硕士输的很惨
找工作ing10:就是这样不是硕士不愿意脱下长衫,是人家觉得屈才了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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