LeetCode:Palindrome Linked List
来源:互联网 发布:阿里云 地区选择 编辑:程序博客网 时间:2024/06/17 17:09
Total Accepted: 28267 Total Submissions: 113712 Difficulty: Easy
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?
Subscribe to see which companies asked this question
思路:
1.用一个“快”指针(fast)和“慢”指针(slow),同时后移。两个指针的后移速度是:fast = 2*slow,即slow走一步,fast走两步。
2.slow指针最终的位置链表的中间位置。
3.将前半部分链表逆置。
4.比较两个部分。
code:
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */public class Solution { public boolean isPalindrome(ListNode head) { if(head == null) { return true; } ListNode slow = head; ListNode fast = head; ListNode p = slow.next; ListNode pre = slow; //find mid pointer, and reverse head half part while(fast.next != null &&fast.next.next != null) { fast = fast.next.next; pre = slow; slow = p; p = p.next; slow.next = pre; } //odd number of elements, need left move slow one step if(fast.next == null) slow = slow.next; slow = slow.next; p = p.next; } return true; }}
0 0
- LeetCode Palindrome Linked List
- LeetCode - Palindrome Linked List
- leetcode: Palindrome Linked List
- Leetcode: Palindrome Linked List
- leetcode:Palindrome Linked List
- [LeetCode] Palindrome Linked List
- LeetCode || Palindrome Linked List
- 【leetcode】Palindrome Linked List
- LeetCode-Palindrome Linked List
- Leetcode|Palindrome Linked List
- [leetcode] Palindrome Linked List
- [LeetCode]Palindrome Linked List
- [Leetcode]Palindrome Linked List
- [leetcode] Palindrome Linked List
- [leetCode] Palindrome Linked List
- LeetCode----Palindrome Linked List
- LeetCode:Palindrome Linked List
- LeetCode Palindrome Linked List
- c#.net smtp 发送邮件
- AndroidManifest.xml文件解析
- SAE 配置预装 django1.8.3中出现的问题
- Linux下如何指定某一类型程序用特定程序打开(通过binfmt_misc)
- mybatis:java.lang.IllegalArgumentException:Parameter Maps collection does notcontain value for ...
- LeetCode:Palindrome Linked List
- 109 You want to take a complete database backup using RMAN. The backup should consist only the used
- 1、Two Sum
- Reachability实时网络监听/AFNETWorking2.0+ 网络监听
- 【bzoj4065】Graphic Madness
- Oracle语句的再深化--转码
- ASP.NET应用程序与页面生命周期
- 求二进制数中1的个数
- 浅析struts2中的验证