链表问题---判断一个链表是否为回文结构

【题目】

给定一个链表的头节点head,请判断该链表是否为回文结构。
  进阶:如果链表长度为N,要求时间复杂度O(N),空间复杂度O(1)。

【基本思路】

方法一。时间复杂度O(N),空间复杂度O(N)。
  
  使用栈,遍历一遍链表把每个节点都压入栈中,这样在弹出栈的时候,所有的节点就逆序了。依次对比原链表的每个节点即可。

#python3.5
def isPalindrome1(head):
    if head == None or head.next == None:
        return True
    stack = []
    cur = head
    while cur != None:
        stack.append(cur)
        cur = cur.next
    while stack:
        if stack.pop().val != head.val:
            return False
        head = head.next
    return True

方法二。时间复杂度O(N),空间复杂度O(N/2)。
  
  也使用栈,但是这次只将链表的后半部分压入栈中,这样在弹出栈的时候,后半部分的节点就逆序了。依次对比链表的前半部分和逆序后的后半部分的每个节点即可。

def isPalindrome2(head):
    if head == None or head.next == None:
        return True
    stack = []
    pre = head.next
    cur = head
    while cur.next != None and cur.next.next != None:
        pre = pre.next
        cur = cur.next.next
    while pre != None:
        stack.append(pre)
        pre = pre.next
    while stack:
        if stack.pop().val != head.val:
            return False
        head = head.next
    return True

方法三。时间复杂度O(N),空间复杂度O(1)。
  
  首先改变链表右半区的结构,使整个右半区的指针反指,中间节点的next指向None。接下来从两端开始向中间依次对比即可。需要注意的是,再判断完毕后要将链表调整会原链表的结构。

def isPalindrome3(head):
    if head == None or head.next == None:
        return True
    pre = head
    cur = head
    while cur.next != None and cur.next.next != None:
        pre = pre.next 
        cur = cur.next.next
    node = pre.next
    pre.next = None 
    while node != None:
        next = node.next
        node.next = pre
        pre = node
        node = next
    node = pre
    res = True
    while pre != None and head != None:
        if pre.val != head.val:
            res = False
            break
        pre = pre.next
        head = head.next
    pre = node.next
    node.next = None
    while pre != None:
        next = pre.next
        pre.next = node
        node = pre
        pre = next
    return res

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值