您的位置:首页 > 编程语言 > Java开发

LeetCode:234. Palindrome Linked List 回文链表 Java

2016-09-04 13:25 531 查看
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

回文链表


题目描述

请编写一个函数,检查链表是否为回文。

给定一个链表ListNode* pHead,请返回一个bool,代表链表是否为回文。
测试样例:
{1,2,3,2,1}

返回:true


{1,2,3,2,3}

返回:false


public class Palindrome {
public boolean isPalindrome(ListNode pHead){
ListNode fast = pHead;
ListNode slow = pHead;
Stack<Integer> stack = new Stack<Integer>();
/**
* 将链表的前半部分元素装入栈中,当快速runner
*(移动的速度是慢速runner的两倍)
* 到底链表尾部时,则慢速runner已经处于链表中间位置
*/
while(fast != null && fast.next != null){
stack.push(slow.val);
slow = slow.next;
fast = fast.next.next;
}
//当链表为奇数个时,跳过中间元素
if (fast != null) {
slow = slow.next;
}
while(slow != null){
//如果两者不相同,则该链表不是回文串
if (stack.pop() != slow.val) {
return false;
}
slow = slow.next;
}
return true;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: