Given a singly linked list, determine if it is a palindrome.
Example 1:
Input: 1->2Output: false
Example 2:
Input: 1->2->2->1Output: true
Follow up: Could you do it in O(n) time and O(1) space?
思路比较清晰直观, 步骤如下:
该题与题目 143.Reorder_List 十分类似。
步骤图解:
第一步: 找中点, 分割链表;qsdummy -> 1 -> 2 -> 2 -> 1 -> NULL..qsdummy -> 1 -> 2 -> 2 -> 1 -> NULLleft 链表:1 -> 2 -> nullright 链表:2 -> 1 -> null第二步: 翻转右边的链表节点;left 链表:1 -> 2 -> nullright 链表:1 -> 2 -> null第三步: 判断 left 链表与 right 链表;
/*** Definition for singly-linked list.* function ListNode(val) {* this.val = val;* this.next = null;* }*//*** @param {ListNode} head* @return {boolean}*/var isPalindrome = function(head) {const dummy = new ListNode(0)dummy.next = headlet slow = dummy, quick = dummywhile (quick && quick.next) {slow = slow.nextquick = quick.next.next}let right = slow.nextslow.next = nulllet left = dummy.nextright = reverseLink(right)while (left && right) {if (left.val !== right.val) {return false}left = left.nextright = right.next}return true}function reverseLink(list) {const dummy = new ListNode(0)dummy.next = listlet prev = nulllet cur = dummy.nextwhile (cur) {const next = cur.nextcur.next = prevprev = curcur = next}return prev}