【LeetCode】Python实现-234. 回文链表
2019-03-10 21:42
399 查看
请判断一个链表是否为回文链表。
示例1:
输入: 1->2
输出: false
示例2:
输入: 1->2->2->1
输出: true
别人的解答:
设置快慢指针,当快指针走完时,慢指针刚好走到中点,随即原地将后半段反转,然后进行回文判断。该解法:空间复杂度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 is None or head.next is None: return True if head.next.next is None: return head.val == head.next.val fast = slow = q = head while fast.next and fast.next.next: #这里快指针的判读条件跟判断环形有一点不同 fast = fast.next.next slow = slow.next def reverse_list(head): if head is None: return head cur = head pre = None nxt = cur.next while nxt: cur.next = pre pre = cur cur = nxt nxt = nxt.next cur.next = pre return cur p = reverse_list(slow.next) while p.next: if p.val != q.val: return False p = p.next q = q.next return p.val == q.val
相关文章推荐
- leetcode 将已排序的 数组/链表 转换为二叉搜索树(BST),Python实现
- leetcode的python实现 刷题笔记9:回文数 暴力解法和进阶算法
- leetcode Rotate list (链表旋转)的python实现
- Python3实现的判断回文链表算法示例
- LeetCode - 234. 回文链表
- LeetCode5.python实现:最长回文子串问题☆☆
- 编程集训第2天:LeetCode--环形链表2(142)及单链表反转(206)C++和python代码实现
- 【LeetCode】Python实现-160. 相交链表
- LeetCode探索模块初级算法链表章节python3代码实现
- 【LeetCode】Python实现-237. 删除链表中的节点
- LeetCode21.python实现: 合并两个有序链表问题☆
- Leetcode[142][206] python实现 链表
- Leetcode 234. 回文链表
- LeetCode 68 Text Justification(Python详解及实现)
- Leetcode做题日记:24. 两两交换链表中的节点(PYTHON)
- Python实现双向链表的基本操作
- [LeetCode] 21. Merge Two Sorted Lists 合并两个有序链表 @python
- [LeetCode-234] Palindrome Linked List(回文链表、链表中间节点查找)
- python:链表定义以及实现
- leetcode-初级-链表-回文链表(JavaScript)(完美满足要求)