算法-回文链表-24

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     public int val;
 *     public ListNode next;
 *     public ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode ReverseList(ListNode head) {
        if(head == null) return null;
        Stack<ListNode> stack = new Stack<ListNode>(5001);//加了这里,速度快了4ms
        while(head != null)
        {
            stack.Push(head);
            head = head.next;
        }
        var rt = stack.Pop();
        var pre = rt;
        while(stack.Count != 0)
        {
            var temp = stack.Pop();
            temp.next = null;
            pre.next = temp;
            pre = pre.next;
        }

        return rt;
    }
}

可以看见每次数组扩容是挺费时间,每次初始化线性表,都要预估一个合理的最大值。现在内存是很大的,以尽量减少时间为主。

posted @ 2023-04-15 22:45  vba是最好的语言  阅读(10)  评论(0编辑  收藏  举报