题目描述
请编写一个函数,检查链表是否为回文。
给定一个链表ListNode* pHead,请返回一个bool,代表链表是否为回文。
测试样例:
{1,2,3,2,1}
返回:true
{1,2,3,2,3}
返回:false
import java.util.*;
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Palindrome {
public boolean isPalindrome(ListNode pHead) {
// write code here
// write code here
int length = 0; //链表长度
ListNode pHeadlength = pHead;
while (pHeadlength.next != null) {
length++;
pHeadlength = pHeadlength.next;
}
length++;
Stack<Integer> stack = new Stack<Integer>();
if (length % 2 == 1) { //如果是奇数个,中间节点不存
for (int i = 0; i < length / 2; i++) {
stack.push(pHead.val);
pHead = pHead.next;
}
pHead = pHead.next;
} else {
for (int i = 0; i < length / 2; i++) {
stack.push(pHead.val);
pHead = pHead.next;
}
}
while (pHead != null) {
if (pHead.val != stack.pop()) {
return false;
}
pHead=pHead.next;
}
return true;
}
}