public class Palindrome {
public boolean isPalindrome(ListNode pHead) {
// write code here
ListNode slow = pHead, fast = pHead;
Stack<Integer> stack = new Stack<Integer>();
//快慢指针把前半截压栈
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(slow.val!=stack.pop())
return false;
slow = slow.next;
}
return true;
}
}
题目描述
public class Palindrome {
public boolean isPalindrome(ListNode pHead) {
// write code here
ListNode slow = pHead, fast = pHead;
Stack<Integer> stack = new Stack<Integer>();
//快慢指针把前半截压栈
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(slow.val!=stack.pop())
return false;
slow = slow.next;
}
return true;
}
}
请编写一个函数,检查链表是否为回文。
给定一个链表ListNode* pHead,请返回一个bool,代表链表是否为回文。
测试样例:
{1,2,3,2,1}
返回:true
{1,2,3,2,3}
返回:false