[Leetcode] 234. Palindrome Linked List
判斷是否是回文
Given a singly linked list, determine if it is a palindrome.
Example 1:
Input: 1->2 Output: false
Example 2:
Input: 1->2->2->1 Output: true
- 先將串列放入list內
- 判斷第一的位置和最後一個位置的數值相減是否為0,若不為0,則記數+1
- 判斷記數是否為0,若為0 則True ,反之 False
Python
# 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: ListNode
:rtype: bool
"""
tem=[]
count = 0
while(head!= None ):
tem.append(head.val)
head=head.next
length=len(tem)/2
if(length==0):
return True
else:
for i in range(length):
if(tem[i]-tem[-i-1] != 0):
count+=1
留言
張貼留言