234. Palindrome Linked List
来源:互联网 发布:传奇 放技能 编程 编辑:程序博客网 时间:2024/06/07 13:10
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 nodedef 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 taildef 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 = Noneclass 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 Truehead=gen_ListNode([1,2,3,4,3,2,1])show_List(head)s=Solution()s.isPalindrome(head)1 → 2 → 3 → 4 → 3 → 2 → 1True
Submission Result:
Status: Accepted
Runtime: 160 ms
Ranking: beats 35.55%
0 0
- 234. Palindrome Linked List
- 234. Palindrome Linked List
- 234. Palindrome Linked List
- 234. Palindrome Linked List
- 234. Palindrome Linked List
- 234. Palindrome Linked List
- 234. Palindrome Linked List
- 234. Palindrome Linked List
- 234. Palindrome Linked List
- 234. Palindrome Linked List
- 234. Palindrome Linked List
- 234. Palindrome Linked List
- 234. Palindrome Linked List
- 234. Palindrome Linked List
- 234. Palindrome (Linked List)
- 234. Palindrome Linked List
- 234. Palindrome Linked List
- 234. Palindrome Linked List
- hdu 2239 Selecting Courses(二分图最大匹配)
- ObjectAnimator之android:propertyName
- 基于UAAG2.0 Reference的移动无障碍案例(一)
- HDU 2199 Can you solve this equation?(二分)
- HDU 3363--贪心
- 234. Palindrome Linked List
- 主流PHP框架之间的比较
- 欢迎使用CSDN-markdown编辑器
- Hdu1248 寒冰王座
- Codeforces 435A Queue on Bus Stop
- 278. First Bad Version
- PRML学习
- 欢迎使用CSDN-markdown编辑器
- 顺序表查询