您好,欢迎来到华佗小知识。
搜索
您的当前位置:首页编程导航打卡第二关链表反转|青铜

编程导航打卡第二关链表反转|青铜

来源:华佗小知识

虚拟结点法

用temp提前记录下一个要反转的结点

public static ListNode reverseList(ListNode head){
    ListNode ans= new ListNode(-1);
    ListNode cur = head;
        while (cur != null) {
            ListNode temp = cur.next;
            cur.next = ans.next;
            ans.next = cur;
            cur = temp;
        }
    return ans.next;
}

不用虚拟头结点

使用三个指针,cur,prev,next。返回的是prev

public static ListNode reverseList(ListNode head){
    ListNode prev=null;
    ListNode cur=head;
    while(cur!=null){
        ListNode next=cur.next;
        cur.next=prev;
        prev=cur;
        cur=next;
    }
    return prev;
}

拓展

递归

public static 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 nexHead;
}

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- huatuo0.cn 版权所有 湘ICP备2023017654号-2

违法及侵权请联系:TEL:199 18 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务