您的位置:首页 > 其它

234. Palindrome Linked List

2016-07-26 19:41 381 查看

234. Palindrome Linked List

Leetcode link for this question

Discription:

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?

Analyze:

#Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
#Generate a linked list by a list and return the head node
def gen_ListNode(li):
if not li:
return None
head=ListNode(li.pop(0))
tmp=head
while li:
tmp.next=ListNode(li.pop(0))
tmp=tmp.next
return head
#Print a linked list from head to tail
def show_List(head):
if not head:
print empty
while head:
print head.val,
if head.next:
print '→',
head=head.next
print


Code 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:
return True
le=0
pre=ListNode('x')
pre.next=head
while head:
le+=1
head=head.next
if le==1:
return True
lo=0
flag=pre.next
while lo<le/2-1 :
old_flag=flag
old_flne=flag.next
old_flnene=flag.next.next

flag.next=old_flnene
old_flne.next=pre.next
pre.next=old_flne

lo+=1
#print le,flag.val
head=pre.next
if le%2:
flag=flag.next
a=pre.next
b=flag.next
while b:
if a.val!=b.val:
return False
a=a.next
b=b.next
return True

head=gen_ListNode([1,2,3,4,3,2,1])
show_List(head)
s=Solution()
s.isPalindrome(head)

1 → 2 → 3 → 4 → 3 → 2 → 1

True


Submission Result:

Status: Accepted

Runtime: 160 ms

Ranking: beats 35.55%
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: