/** * 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; } }
可以看见每次数组扩容是挺费时间,每次初始化线性表,都要预估一个合理的最大值。现在内存是很大的,以尽量减少时间为主。
标签:24,pre,head,ListNode,public,链表,next,stack,回文 From: https://www.cnblogs.com/Insist-Y/p/17322153.html