234. Palindrome Linked List
2017-01-12 07:20
330 查看
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?
判断一个链表是不是构成回文。如果是数组时,我们会从中间开始向两边比较是不是相等。那么换作链表,只能单向访问,怎么办?可以从中间node开始,后半部分进行反转,然后从最后一个node开始,跟第一个node依次往中间对比。代码如下:
/**
* 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;
}
//find middle Node
ListNode fastNode = head;
ListNode slowNode = head;
boolean isodd = false;
while (fastNode != null && fastNode.next != null) {
slowNode = slowNode.next;
fastNode = fastNode.next.next;
}
//reverse back part list
ListNode preNode = null;
ListNode currNode = slowNode;
ListNode nextNode = null;
while (currNode != null) {
nextNode = currNode.next;
currNode.next = preNode;
preNode = currNode;
currNode = nextNode;
}
//compare front and back part list
while (preNode != null) {
if (preNode.val != head.val) {
return false;
}
preNode = preNode.next;
head = head.next;
}
return true;
}
}
Follow up:
Could you do it in O(n) time and O(1) space?
判断一个链表是不是构成回文。如果是数组时,我们会从中间开始向两边比较是不是相等。那么换作链表,只能单向访问,怎么办?可以从中间node开始,后半部分进行反转,然后从最后一个node开始,跟第一个node依次往中间对比。代码如下:
/**
* 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;
}
//find middle Node
ListNode fastNode = head;
ListNode slowNode = head;
boolean isodd = false;
while (fastNode != null && fastNode.next != null) {
slowNode = slowNode.next;
fastNode = fastNode.next.next;
}
//reverse back part list
ListNode preNode = null;
ListNode currNode = slowNode;
ListNode nextNode = null;
while (currNode != null) {
nextNode = currNode.next;
currNode.next = preNode;
preNode = currNode;
currNode = nextNode;
}
//compare front and back part list
while (preNode != null) {
if (preNode.val != head.val) {
return false;
}
preNode = preNode.next;
head = head.next;
}
return true;
}
}
相关文章推荐
- 成小胖学习微服务架构·基础篇
- 微软Project Springfield团队的F#使用心得
- 实现BUG自动检测 - ASP.NET Core依赖注入
- 证明技巧I——反证法
- VMware Workstations与Windows共享文件夹
- 进程与线程的区别(概念理解)
- compose的secure-http属性怎么全局设置成false
- 80老翁谈人生(340):网络空间法制化,立法先行,任重道远
- Python类的定义使用 《Head First Python》第六章
- 281. Zigzag Iterator
- Leetcode 447. Number of Boomerangs
- LeetCode Assign Cookies
- 298. Binary Tree Longest Consecutive Sequence
- 计算机网络——介质访问控制子层
- 【数据结构与算法】排序
- 482. License Key Formatting
- exercise 31 做决定
- Elastic Distributed Database
- (未艾原创)当当当当!!!真正的第一篇博文!!Ajax发送请求及处理。(我在新浪博客的第一篇文章)
- exercise 30 else and if 语句