[LeetCode][JavaScript]Palindrome Linked List
Palindrome Linked List
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?
https://leetcode.com/problems/palindrome-linked-list/
判断单链表是否为回文,要求时间复杂度O(n),空间复杂度O(1)。
如果对空间复杂度没有要求,有两种简单的做法。
一种是开个数组,把链表里的值挨个塞进去,然后双指针。
还有一种是做一轮遍历,把单链表变成双链表(javasrcipt可以修改实例化的对象), 然后双指针。
时间复杂度O(n),空间复杂度O(1)的解法:
1.第一轮遍历用快慢指针(快指针每次走两步,慢指针每次走一步)寻找中点 -> O(n)
2.反转后半段链表 -> O(n/2)
3.比较 -> O(n/2)
合起来时间还是O(n)。
你确定这是easy?
1 /** 2 * Definition for singly-linked list. 3 * function ListNode(val) { 4 * this.val = val; 5 * this.next = null; 6 * } 7 */ 8 /** 9 * @param {ListNode} head 10 * @return {boolean} 11 */ 12 var isPalindrome = function(head) { 13 //find middle 14 var slow = head, fast = head, cacheHead = head; 15 while(fast !== null && fast.next !== null){ 16 slow = slow.next; 17 fast = fast.next.next; 18 } 19 20 //reverse link list 21 var list2Head = new ListNode("head"), tmp; 22 while(slow !== null){ 23 tmp = slow; 24 slow = slow.next; 25 tmp.next = list2Head.next; 26 list2Head.next = tmp; 27 } 28 29 //judge palindrom 30 var list1 = cacheHead, list2 = list2Head.next; 31 for(; list2 !== null; list1 = list1.next, list2 = list2.next){ 32 if(list1.val !== list2.val){ 33 return false; 34 } 35 } 36 return true; 37 };