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