LeetCode_CC150
  • Introduction
  • LeetCode
    • Single Number
    • Contains Duplicate
    • Happy Number
    • Valid Anagram
    • Contains Duplicate II
    • Count Primes
    • Isomorphic Strings
    • Word Pattern
    • Island Perimeter
    • Find the Difference
    • Palindrome Permutation
    • Two Sum III - Data structure design
    • Number of Boomerangs
    • Longest Palindrome
    • Logger Rate Limiter
    • Find All Anagrams in a String
    • Keyboard Row
    • Distribute Candies
    • Shortest Word Distance
    • Majority Element
    • Plus One
    • Best Time to Buy and Sell Stock
    • Best Time to Buy and Sell Stock II
    • Pascal's Triangle
    • Remove Element
    • Rotate Array
    • Pascal's Triangle II
    • Two Sum II - Input array is sorted
    • Third Maximum Number
    • Max Consecutive Ones
    • K-diff Pairs in an Array
    • Maximum Product of Three Numbers
    • Maximum Distance in Arrays
    • Shortest Unsorted Continuous Subarray
    • Roman to Integer
    • Count and Say
    • Valid Parentheses
    • Longest Common Prefix
    • Valid Palindrome
    • Length of Last Word
    • Repeated Substring Pattern
    • Number of Segments in a String
    • Valid Word Abbreviation
    • Longest Uncommon Subsequence I
    • Student Attendance Record I
    • Reverse Words in a String III
    • Arranging Coins
    • Guess Number Higher or Lower
    • Search Insert Position
    • Min Stack
    • Diameter of Binary Tree
    • Unique Binary Search Trees
    • Unique Binary Search Trees II
    • Binary Tree Zigzag Level Order Traversal
    • Nim Game
    • Add Digits
    • Fizz Buzz
    • Climbing Stairs
    • Array Partition I
    • Power of Three
    • Power of Four
    • Power of Two
    • Ugly Number
    • Find All Numbers Disappeared in an Array
    • Find All Duplicates in an Array
    • Minimum Moves to Equal Array Elements
    • Meeting Rooms
    • Subsets
    • Subsets II
    • Count Complete Tree Nodes
    • Minimum Size Subarray Sum
    • Maximum Size Subarray Sum Equals k
    • Sparse Matrix Multiplication
    • Meeting Rooms II
    • Letter Combinations of a Phone Number
    • Binary Tree Vertical Order Traversal
    • Find the Celebrity
    • Merge Intervals
    • One Edit Distance
    • Multiply Strings
  • Array&String
    • Subarray Sum
    • Maximum Subarray
    • Intersection of Two Arrays
    • Intersection of Two Arrays II
    • Partition List
    • Merge Sorted Array
    • Two Sum
    • 3Sum
    • Product of Array Except Self
    • Rotate Image
    • Spiral Matrix
  • Linked List
    • Merge Two Sorted Lists
    • Insert into a Cyclic Sorted List
    • Sort List
    • Linked List Cycle
    • Copy List with Random Pointer
    • Add Two Numbers
    • Delete Node in a Linked List
    • Reverse Linked List
    • Odd Even Linked List
    • Intersection of Two Linked Lists
    • Palindrome Linked List
    • Insertion Sort List
    • Remove Linked List Elements
    • Remove Duplicates from Sorted List
    • Swap Nodes in Pairs
    • Remove Nth Node From End of List
  • Binary Search
    • Missing Number
    • Valid Perfect Square
    • 744. Find Smallest Letter Greater Than Target
    • Sqrt(x)
    • First Bad Version
    • Pow(x, n)
    • Find the Duplicate Number
    • Find Minimum in Rotated Sorted Array
    • Find Minimum in Rotated Sorted Array II
    • Total Occurrence of Target
    • Search in a Big Sorted Array
    • Longest Increasing Subsequence
    • Find Peak Element
    • Search in Rotated Sorted Array
    • Search a 2D Matrix
    • Search a 2D Matrix II
    • Closest Number in Sorted Array
    • Search in Rotated Sorted Array II
    • Search for a Range
    • Maximum Number in Mountain Sequence
    • Last Position of Target
    • K Closest Numbers In Sorted Array
    • Sqrt(x) II
  • Binary Tree
    • Maximum Depth of Binary Tree
    • Invert Binary Tree
    • Same Tree
    • Binary Tree Paths
    • Lowest Common Ancestor of a Binary Search Tree
    • Balanced Binary Tree
    • Convert Sorted Array to Binary Search Tree
    • Symmetric Tree
    • Path Sum
    • Minimum Depth of Binary Tree
    • Binary Tree Preorder Traversal
    • Binary Tree Inorder Traversal
    • Binary Tree Level Order Traversal
    • Binary Tree Level Order Traversal II
    • Minimum Subtree
    • Flatten Binary Tree to Linked List
    • Binary Tree Longest Consecutive Sequence
    • Subtree with Maximum Average
    • Number of Islands
    • Serialize and Deserialize Binary Tree
    • Clone Graph
  • Data Structure
    • Hash Table
    • Bubble Sort
    • Selection Sort
    • Binary Search
    • Merge Sort
    • Binary Tree
    • 递归
    • DFS BFS
    • python技巧
  • two pointers
    • Reverse Vowels of a String
    • Reverse String
    • Remove Duplicates from Sorted Array
    • LeetCode 11. Container With Most Water
    • Strobogrammatic Number
    • Move Zeroes
    • Implement strStr()
  • 哈希表
    • Ransom Note
    • Minimum Index Sum of Two Lists
    • Longest Harmonious Subsequence
    • Untitled
Powered by GitBook
On this page

Was this helpful?

  1. Linked List

Palindrome Linked List

PreviousIntersection of Two Linked ListsNextInsertion Sort List

Last updated 5 years ago

Was this helpful?

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?

这道题让我们判断一个链表是否为回文链表,LeetCode中关于回文串的题共有六道,除了这道,其他的五道为,,,和.链表比字符串难的地方就在于不能通过坐标来直接访问,而只能从头开始遍历到某个位置。那么根据回文串的特点,我们需要比较对应位置的值是否相等,那么我们首先需要找到链表的中点,这个可以用快慢指针来实现,使用方法可以参见之前的两篇和,我们使用快慢指针找中点的原理是fast和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

        # 1. Get the midpoint (slow)
        slow = fast = cur = head
        while fast and fast.next:
            fast, slow = fast.next.next, slow.next

        # 2. Push the second half into the stack
        stack = [slow.val]
        while slow.next:
            slow = slow.next
            stack.append(slow.val)

        # 3. Comparison
        while stack:
            if stack.pop() != cur.val:
                return False
            cur = cur.next
        return True

这道题的Follow Up让我们用O(1)的空间,那就是说我们不能使用stack了,那么如果代替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
        """
        fast = slow = head
        # find the mid node
        # 一般走两步的都会是两个判断条件
        while fast and fast.next:
            fast = fast.next.next
            slow = slow.next
        pre = None
        while slow:
            nxt = slow.next
            slow.next = pre
            pre= slow
            slow = nxt
        # compare the first and second half nodes
        while pre:  # while node and head:
            if pre.val != head.val:
                return False
            pre = pre.next
            head = head.next
        return True

二刷:

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 not head or not head.next:
            return True
        slow = head
        fast = head.next
        stack = [head.val]
        while fast and fast.next:
            slow = slow.next
            fast = fast.next.next
            stack.append(slow.val)
        # 通过while lopp后,fast是不是none来判断linkedlist个数是奇数还是偶数,如果是奇数,mid停留在正中间,stack=[1,2,3]后半部分为2,1,需要先pop出3,再进行比较
        if not fast:
            stack.pop()
        while slow.next:
            slow = slow.next
            node = stack.pop()
            if slow.val != node:
                return False
        return True

2。

注意fast和slow的初始条件都是head, 并且while终止条件是fast and fast.next。这样循环结束时slow停留在中间靠后的位置(偶数个node)。便于我们再反转的时候起始值准确的对应后半部分

Palindrome Number 验证回文数字
Validate Palindrome 验证回文字符串
Palindrome Partitioning 拆分回文串
Palindrome Partitioning II 拆分回文串之二
Longest Palindromic Substring 最长回文串
Convert Sorted List to Binary Search Tree 将有序链表转为二叉搜索树
Reorder List 链表重排序