LeetCode笔记:206. Reverse Linked List

题目:

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

合集:https://github.com/Cloudox/LeetCode-Record
版权所有:http://blog.csdn.net/cloudox_

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值