请判断一个链表是否为回文链表。
示例 1:
输入: 1->2
输出: false
示例 2:
输入: 1->2->2->1
输出: true
参考答案:
利用链表的后续遍历,使用函数调用栈作为后序遍历栈,来判断是否回文
1var isPalindrome = function(head) { 2 let left = head; 3 function traverse(right) { 4 if (right == null) return true; 5 let res = traverse(right.next); 6 res = res && (right.val === left.val); 7 left = left.next; 8 return res; 9 } 10 return traverse(head); 11};
通过快、慢指针找链表中点,然后反转链表,比较两个链表两侧是否相等,来判断是否是回文链表
1var isPalindrome = function(head) { 2 // 反转 slower 链表 3 let right = reverse(findCenter(head)); 4 let left = head; 5 // 开始比较 6 while (right != null) { 7 if (left.val !== right.val) { 8 return false; 9 } 10 left = left.next; 11 right = right.next; 12 } 13 return true; 14} 15function findCenter(head) { 16 let slower = head, faster = head; 17 while (faster && faster.next != null) { 18 slower = slower.next; 19 faster = faster.next.next; 20 } 21 // 如果 faster 不等于 null,说明是奇数个,slower 再移动一格 22 if (faster != null) { 23 slower = slower.next; 24 } 25 return slower; 26} 27function reverse(head) { 28 let prev = null, cur = head, nxt = head; 29 while (cur != null) { 30 nxt = cur.next; 31 cur.next = prev; 32 prev = cur; 33 cur = nxt; 34 } 35 return prev; 36} 37
最近更新时间:2021-07-25