Leetcode 234. Palindrome Linked List
来源:互联网 发布:网络手势图片意思 编辑:程序博客网 时间:2024/06/11 19:42
234. Palindrome Linked List
Total Accepted: 69120 Total Submissions: 225579 Difficulty: EasyGiven a singly linked list, determine if it is a palindrome.
Follow up:
Could you do it in O(n) time and O(1) space?
Hide Similar Problems
思路:
解法一:
n空间的做法是遍历到中间之后把slow.next开始的所有元素入栈。无论奇偶slow.next永远是要做对比的元素。然后做对比。
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */public class Solution { // 6ms public boolean isPalindrome(ListNode head) { if(head == null) return true; ListNode slow = head; ListNode fast = head; while(fast.next != null && fast.next.next!=null){ slow = slow.next; fast = fast.next.next; } Stack<Integer> st = new Stack<>(); fast = slow.next; while(fast != null){ st.push(fast.val); fast = fast.next; } while(!st.isEmpty()){ if(st.pop() != head.val) return false; head = head.next; } return true; }}
解法二:
常数空间。从以slow作为dummy head,把之后的元素翻转。然后slow = slow.next 在slow != null的时候和head元素对比。
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */public class Solution { // 2ms public boolean isPalindrome(ListNode head) { if(head == null) return true; ListNode slow = head; ListNode fast = head; while(fast.next != null && fast.next.next!=null){ slow = slow.next; fast = fast.next.next; } fast = slow.next; slow.next = null; while(fast != null){ ListNode next = fast.next; fast.next = slow.next; slow.next = fast; fast = next; } slow = slow.next; while(slow !=null){ if(slow.val != head.val) return false; slow = slow.next; head = head.next; } return true; }}
0 0
- [leetcode] 234.Palindrome Linked List
- [LeetCode]234.Palindrome Linked List
- [leetcode] 234.Palindrome Linked List
- 【leetcode】234. Palindrome Linked List
- 【LeetCode】234. Palindrome Linked List
- [leetcode] 234. Palindrome Linked List
- 234. Palindrome Linked List LeetCode
- LeetCode--234. Palindrome Linked List
- LeetCode 234. Palindrome Linked List
- 【LeetCode】234. Palindrome Linked List
- leetcode 234. Palindrome Linked List
- LeetCode *** 234. Palindrome Linked List
- LeetCode 234. Palindrome Linked List
- leetcode-234. Palindrome Linked List
- LeetCode-234.Palindrome Linked List
- 【LeetCode】234. Palindrome Linked List
- [Leetcode]234. Palindrome Linked List
- 【leetcode】234. Palindrome Linked List
- 安卓驱动开发之-(二)硬件访问服务_框架
- 使用NetBeans访问CSDN Code项目
- Java IO中转换流的作用
- Hive 笔记异常
- Tiny tiny RSS安装
- Leetcode 234. Palindrome Linked List
- 使用数据结构,最大上升子串问题
- 剑指Offer 24题 二叉搜索树的后序遍历序列 Java
- 拒绝从入门到放弃_《鸟哥的 Linux 私房菜 — 基础学习篇(第三版)》必读目录
- Python.You-Get -- Python的视频下载工具[推荐玩玩]
- notepad++ key words 设置
- Uva1451 数形结合
- solve 方法总结
- DIV与前面的控件在同一行显示.