首页 > 其他 > 详细

c_nk_反转链表(迭代/递归)

时间:2020-10-20 16:45:32      阅读:37      评论:0      收藏:0      [点我收藏+]

输入一个链表,反转链表后,输出新链表的表头。

思路
还是递归好想
技术分享图片

class Solution {
    public ListNode ReverseList(ListNode head) {
        if (head==null || head.next==null) return head;
        ListNode newHead=ReverseList(head.next);
        head.next.next=head;
        head.next=null;
        return newHead;
    }
}

迭代,你指针赋值之前一定要保存下一个指针在哪,不然会找不到
技术分享图片

class Solution {
    public ListNode ReverseList(ListNode head) {
        if (head==null || head.next==null) return head;
        ListNode pre=null, post=head;
        while (head!=null) {
            post=head.next;
            head.next=pre;
            pre=head;
            head=post;
        }
        return pre;
    }
}

c_nk_反转链表(迭代/递归)

原文:https://www.cnblogs.com/wdt1/p/13846418.html

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