(一)需求
回文链表,想了很久,怎么移动都都会很多奇怪的情况出现。比如[1]也是回文。
(二)回文链表
1、问题描述
给你一个单链表的头节点 head
,请你判断该链表是否为回文链表。如果是,返回 true
;否则,返回 false
。
输入:head = [1,2,2,1]
输出:true
2、思路:
- 将每个节点的值push到数组中
- 数组反转
- 判断数组反转前后是否相等就能判断出是否是回文
3、代码
/**
* Definition for singly-linked list.
* class ListNode {
* val: number
* next: ListNode | null
* constructor(val?: number, next?: ListNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
* }
*/
function isPalindrome(head: ListNode | null): boolean {
let arr = []
let node= head
while(node){
arr.push(node.val)
node=node.next
}
let s1=arr.join('')
let s2=arr.reverse().join('')
return s1===s2?true:false
};
空间复杂度将是 O(n)
时间复杂度将是 O(n)
以上
参考链接
https://leetcode.cn/leetbook/read/linked-list/fov6t/
写在最后的话
学习路上,常常会懈怠
《有想学技术需要监督的同学嘛~》
https://mp.weixin.qq.com/s/FyuddlwRY7DsHUejCjiVug