Last updated
Was this helpful?
Last updated
Was this helpful?
Given a singly linked list, determine if it is a palindrome.
Follow up: Could you do it in O(n) time and O(1) space?
两种解法,解法一是用stack,一边tranverse链表一边把前半部分放进栈里。这里因为list的长度可能是基数,所以中间会判断一下然后pop掉多余的一个。最后是判断栈里的值是否与后半段一样。用了O(n)的extra space。
解法二:首先找到中点,切开,然后把后半段翻转,然后再比较两条链元素的值。这个只用了O(1) space。