当前位置:网站首页>Nowcoder reverse linked list

Nowcoder reverse linked list

2022-07-04 14:24:00 Fan Qianzhi

describe

Given the head node of a single linked list pHead( The header node has a value , For example, in the figure below , its val yes 1), The length is n, After reversing the linked list , Return the header of the new linked list .

Data range : 0 ≤ n ≤ 10000 0\leq n\leq10000 0n10000
requirement : Spatial complexity O(1), Time complexity O(n).

For example, when entering a linked list {1,2,3} when ,
After reversal , The original linked list becomes {3,2,1}, So the corresponding output is {3,2,1}.
The above conversion process is shown in the figure below :

 Insert picture description here

Ideas

Reverse the linked list with recursive method .

Code

    public ListNode ReverseList(ListNode head) {
    
        if (head == null || head.next == null)
            return head;
        ListNode reverse = ReverseList(head.next);
        head.next.next = head;
        head.next = null;
        return reverse;
    }
原网站

版权声明
本文为[Fan Qianzhi]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/185/202207041222044030.html

随机推荐