zoukankan      html  css  js  c++  java
  • 回文链表

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

    示例 1:
    
    输入: 1->2
    输出: false
    示例 2:
    
    输入: 1->2->2->1
    输出: true
    进阶:
    你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?

    代码思路:

    不考虑空间复杂度的话,这道题其实很容易。但是一旦考虑了空间复杂度,就表示需要对原始链表进行操作。

    首先先利用快慢指针找到原始链表的中间,因为考虑到奇偶,所以slow指针需要往后走一位,保证需要反转的链表是跳过了奇数的中间位,然后再反转后面的链表。这个时候只要保证判断的后面链表不为空就可以了,前面的链表我不管。而且快指针有没有走到头我也不用管,反正一旦不能走了我慢指针一定是在中间的前一位。

    # 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
            slow=fast=head
            while fast.next and fast.next.next:
                
                slow=slow.next
                fast=fast.next.next
                
            
            slow=self.reverseList(slow.next)
            
            while slow:
                if head.val != slow.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
            
  • 相关阅读:
    数据结构-串的堆分配存储
    ServerSocket
    Java-坦克大战
    Java-输入输出流
    MyEclipse 快捷键
    数据结构-串的定长顺序存储
    我的软考资料集合
    软考中级软件设计师考试大纲
    2016年第一季度阅读书目
    中国大陆开源镜像网站汇总
  • 原文地址:https://www.cnblogs.com/guangluwutu/p/10697400.html
Copyright © 2011-2022 走看看