题目描述
请编写一个函数,检查链表是否为回文。
给定一个链表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
if(pHead == null) return false;
ListNode p = pHead;
ListNode head = new ListNode(0);
while(p != null){
ListNode q = new ListNode(p.val);
p = p.next;
q.next = head.next;
head.next = q;
}
head = head.next;
while(head != null){
if(head.val != pHead.val) return false;
head = head.next;
pHead = pHead.next;
}
return true;
}
}