LeetCode 234 [Palindrome Linked List]

原题

设计一种方式检查一个链表是否为回文链表。

样例
1->2->1就是一个回文链表。

解题思路

  • 方法一:快慢指针,慢指针一边走一边将经过的节点放入stack,当快指针走到终点,慢指针正好走到中点,并且已经将前半段放入stack,根据stack的特性,之后依次取出跟后半段比对。
  • 方法二:依旧使用快慢指针,取到中点,然后将后半段翻转,比较

完整代码

# 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
        
        stack = []
        slow, fast = head, head
        while fast != None and fast.next != None:
            stack.append(slow.val)
            slow = slow.next
            fast = fast.next.next
        
        if fast == None:
            pass
        else:
            slow = slow.next
        
        while slow != None:
            cur = stack.pop()
            if slow.val != cur:
                return False
            slow = slow.next
            
        return True
        
# 方法二
class Solution(object):
    def isPalindrome(self, head):
        """
        :type head: ListNode
        :rtype: bool
        """
        if head == None or head.next == None:
            return True
        
        slow, fast = head, head
        while fast != None and fast.next != None:
            slow = slow.next
            fast = fast.next.next
        
        if fast == None:
            secHalf = self.reverse(slow)
        else:
            secHalf = self.reverse(slow.next)
        
        while secHalf != None:
            if secHalf.val != head.val:
                return False
            secHalf = secHalf.next
            head = head.next
            
        return True
    
    def reverse(self, head):
        if not head:
            return head
        
        prev = None
        while head != None:
            temp = head.next
            head.next = prev
            prev = head
            head = temp
        
        return prev  
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容