题目描述:
给你一个单链表的头节点 head
,请你判断该链表是否为
回文链表
。如果是,返回 true
;否则,返回 false
。
示例 1:
输入:head = [1,2,2,1] 输出:true
示例 2:
输入:head = [1,2] 输出:false
提示:
- 链表中节点数目在范围
[1, 105]
内 0 <= Node.val <= 9
我的作答:
我的思路是先复制一个一样的链表,再反转这个复制的链表,一个结点一个结点比较,碰到不一样的就return false
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):def isPalindrome(self, head):""":type head: Optional[ListNode]:rtype: bool"""if not head: return Truedef copylist(head): #复制链表dummy = ListNode(0)cur = dummywhile head:cur.next = ListNode(head.val)cur = cur.nexthead = head.nextreturn dummy.next #这个头结点真的好烦def reverse(copy_head): #反转复制的链表cur, pre = copy_head, Nonewhile cur:temp = cur.nextcur.next = prepre = curcur = tempreturn precopy_head = copylist(head)copy_head = reverse(copy_head)cur1, cur2 = head, copy_headwhile cur1 and cur2: #比较if cur1.val!=cur2.val:return Falsecur1 = cur1.nextcur2 = cur2.nextreturn True
缺点是真的很繁琐。。orz
参考:
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):def isPalindrome(self, head):""":type head: Optional[ListNode]:rtype: bool"""# 保证长度大于1,方便一刀两段if not head.next: return True# 遍历一遍得长度# -------------l = 0cur = headwhile cur:cur = cur.nextl += 1# ---------------# 根据长度反转前面一半的链表# -------------------------pre = Nonecur = headi = 0while l//2 != i:nxt =cur.nextcur.next = prepre = curcur = nxti += 1# -----------------------# 长度为奇数,中间的数不用比较if l % 2 == 1: cur = cur.next# 一一对照即可while cur and pre:if cur.val != pre.val:return Falsecur = cur.nextpre = pre.nextreturn True