首页 > 其他 > 详细

LeetCode笔记:206. Reverse Linked List

时间:2016-04-28 17:09:11      阅读:230      评论:0      收藏:0      [点我收藏+]

题目:

Reverse a singly linked list.

大意:

反转一个简单链表。

思路:

题目的意思就是给出一个链表,本来是从头指向尾的,现在要你做成从尾指向头,并且返回原来的尾,现在的头。这个肯定是要用递归或者迭代来做。只要屡清楚过程,会比较绕。大体的流程就是,把下一个节点的next指向自己,一个个迭代、递归下去,最后返回最后的原来的尾节点

他山之石:

这里给出Discuss中最火的方法。
迭代实现:

public ListNode reverseList(ListNode head) {
    /* iterative solution */
    ListNode newHead = null;
    while (head != null) {
        ListNode next = head.next;
        head.next = newHead;
        newHead = head;
        head = next;
    }
    return newHead;
}

递归实现:

public ListNode reverseList(ListNode head) {
    /* recursive solution */
    return reverseListInt(head, null);
}

private ListNode reverseListInt(ListNode head, ListNode newHead) {
    if (head == null)
        return newHead;
    ListNode next = head.next;
    head.next = newHead;
    return reverseListInt(next, head);
}

版权所有:http://blog.csdn.net/cloudox_

LeetCode笔记:206. Reverse Linked List

原文:http://blog.csdn.net/cloudox_/article/details/51274716

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!