请判断一个链表是否为回文链表。
示例 1:
输入: 1->2
输出: false
示例 2:
输入: 1->2->2->1
输出: true
进阶:
你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?
(一) O(n) 时间复杂度
# 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
"""
list = []
cur = head
while cur:
list.append(cur.val)
cur = cur.next
return list == list[::-1]
(二)O(1) 空间复杂度
想法:使用两个指针,当指针一走完时,指针二走到链表一半,将后半部分折叠,并于前半部分直接比较。
参考代码https://blog.csdn.net/qq_34364995/article/details/80640449