【LeetCode 简单题】63-回文链表

声明:

今天是第63道题。请判断一个链表是否为回文链表。以下所有代码经过楼主验证都能在LeetCode上执行成功,代码也是借鉴别人的,在文末会附上参考的博客链接,如果侵犯了博主的相关权益,请联系我删除

(手动比心ღ( ´・ᴗ・` ))

正文

题目:请判断一个链表是否为回文链表。

示例 1:

输入: 1->2
输出: false

示例 2:

输入: 1->2->2->1
输出: true

进阶:
你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?

解法1。用快慢指针找到链表中点(slow最后指向的就是中部),然后让slow指向的后半部分链表逐个与前半部分的节点值相比较,如果一直能相等遍历到结束,就返回True,代码如下。

# 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 not head or not head.next:
            return True
        fast = slow = head
        while(fast.next and fast.next.next):
            slow = slow.next
            fast = fast.next.next
        
        slow = slow.next
        slow = self.reverseList(slow)

        while slow:
            if slow.val != head.val:
                return False
            slow = slow.next
            head = head.next
        return True

    def reverseList(self,head):
        new_head = None
        while head:
            p = head
            head = head.next
            p.next = new_head
            new_head = p
        return new_head
            

结尾

解法1:https://blog.csdn.net/coder_orz/article/details/51306985

猜你喜欢

转载自blog.csdn.net/weixin_41011942/article/details/83590314