leetcode_234. Palindrome Linked List 判断单链表是否为回文串,快慢指针法找中间节点,反转单链表

题目:

Given a singly linked list, determine if it is a palindrome.

Follow up:
Could you do it in O(n) time and O(1) space?


题意:

判断一个单链表是否为回文串,要求用O(n)的时间复杂度和O(1)的空间复杂度


代码:

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None


class Solution(object):
    def isPalindrome(self, head):
        """
        :type head: ListNode
        :rtype: bool
        """
        
        if head == None or head.next == None :
            return True
        else :
            #快慢指针法寻找单链表的中间节点
            fast = ListNode(0)
            slow = ListNode(0)
            new_head = ListNode(0)
            
            fast = head
            slow = head
            
            while fast != None and fast.next != None :
                slow = slow.next
                fast = fast.next.next
            
            #判断单链表节点个数,如果fast不为空,则为奇数个;如果fast为空,则为偶数个
            if fast != None :  #奇数个时,slow指向中间节点,将slow之后的节点反转
                new_head = slow.next
            else :
                new_head = slow
            
            #反转new_head之后的链表
            p = ListNode(0)
            q = ListNode(0)
            p = new_head.next
            q = new_head
            new_head.next = None
            while p != None :
                q = p.next
                p.next = new_head
                new_head = p
                p = q
            
            #比较head和newhead是否是回文串
            p = head
            q = new_head
            while q != None :
                if p.val != q.val :
                    return False
                p = p.next
                q = q.next
            return True
                
 

笔记:

1、学到用快慢指针法寻找单链表的中间节点,参考:http://blog.csdn.net/sunao2002002/article/details/46918645

2、反转单链表,比较是否为回文串




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值