数据结构链表(9)——回文链表

92 阅读1分钟

(一)需求

回文链表,想了很久,怎么移动都都会很多奇怪的情况出现。比如[1]也是回文。

(二)回文链表

1、问题描述

给你一个单链表的头节点 head ,请你判断该链表是否为回文链表。如果是,返回 true ;否则,返回 false

img

输入:head = [1,2,2,1]
输出:true

2、思路:

  1. 将每个节点的值push到数组中
  2. 数组反转
  3. 判断数组反转前后是否相等就能判断出是否是回文

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)

在这里插入图片描述

以上

参考链接

leetcode.cn/leetbook/re…

写在最后的话

学习路上,常常会懈怠

《有想学技术需要监督的同学嘛~》 mp.weixin.qq.com/s/FyuddlwRY…