【链表】回文链表(三种解法)

原题链接

解法一:将所有入栈比对

将所有值入栈,然后出栈进行比对,不相等返回false,相等返回true

  • ts
/**
 * 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 stack = []
    let cur = head
    while (cur) {
        stack.push(cur)
        cur = cur.next
    }
    while (head) {
        if (head.val != stack.pop().val) return false
        head = head.next
    }
    return true
};
  • 时间复杂度 O ( n ) O(n) O(n)
  • 空间复杂度 O ( n ) O(n) O(n)

解法二:快慢指针+栈

首先取到中间元素(快指针两步慢指针一步,快指针跑完,慢指针就在中间)
然后将后半部分入栈
然后出栈比较,直到栈为空

  • ts
function isPalindrome(head: ListNode | null): boolean {
    if (!head || !head.next) return true
    let right = head.next as ListNode
    let cur = head
    while (cur.next && cur.next.next) {
        right = right.next
        cur = cur.next.next
    }
    let stack = []
    while(right){
        stack.push(right)
        right = right.next
    }
    while(stack.length){
        if(stack.pop().val!=head.val)return false
        head = head.next
    }
    return true
}

  • 时间复杂度 O ( l o g N ) O(logN) O(logN)
  • 空间复杂度 O ( l o g N ) O(logN) O(logN)

解法三:快慢指针

首先取到中间元素(快指针两步慢指针一步,快指针跑完,慢指针就在中间)
然后将后半部分逆序
将逆序后的部分依次与开头比较是否相等,对比结束后记录最终状态
将右半部逆序回来

function isPalindrome(head: ListNode | null): boolean {
    if (!head || !head.next) return true
    let n1 = head
    let n2 = head
    while (n2.next && n2.next.next) {
        n1 = n1.next
        n2 = n2.next.next
    }
    n2 = n1.next
    n1.next = null
    let n3: ListNode | null = null
    while (n2) {
        n3 = n2.next
        n2.next = n1
        n1 = n2
        n2 = n3
    }
    n3 = n1
    n2 = head
    let res = true
    while (n1 && n2) {
        if (n1.val != n2.val) res = false
        n1 = n1.next
        n2 = n2.next
    }
    n1 = n3.next
    n3.next = null
    while (n1) {
        n2 = n1.next
        n1.next = n3
        n3 = n1
        n1 = n2
    }
    return res
}
  • 时间复杂度 O ( l o g N ) O(logN) O(logN)
  • 空间复杂度 O ( 1 ) O(1) O(1)
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值