234. Palindrome Linked List
2016-07-26 19:41
381 查看
234. Palindrome Linked List
Leetcode link for this questionDiscription:
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: AcceptedRuntime: 160 ms
Ranking: beats 35.55%
相关文章推荐
- css 定位介绍
- ObjectAnimator之android:propertyName
- 基于UAAG2.0 Reference的移动无障碍案例(一)
- c/c++第二天
- JAVA以UTF-8导出CSV文件,用excel打开产生乱码的解决方法
- 服务化拆分
- 绘图基础二
- 常用 web service
- HDU 5752 Sqrt Bo
- 常见的路由表建立算法
- 每日练习
- 服务化拆分
- 服务化拆分
- HDU 5514 Frogs (容斥原理)
- [SCU4439] Vertex Cover [2015 Sichuan Province Contest Final D]
- Android 开发环境目录结构
- 树莓派 Learning 001 装机 ---之 1 安装NOOBS系统
- 彻底解决安装Python扩展包时Unable to find vcvarsall.bat
- POJ 1064 Cable master (二分)
- 扩展欧几里得定理