华佗小知识
您的当前位置:首页编程导航打卡第二关链表反转|青铜

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

来源:华佗小知识

虚拟结点法

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

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