题目
请编写一个函数,检查链表是否为回文。
给定一个链表ListNode* pHead,请返回一个bool,代表链表是否为回文。
我的题解
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
int len = 0;
ListNode target = null;
ListNode cur = pHead;
while(cur != null) {
len ++;
ListNode node = new ListNode(cur.val);
node.next = target;
target = node;
cur = cur.next;
}
cur = pHead;
for(int i = 0; i < len / 2; i ++) {
if(cur.val != target.val) {
return false;
}
cur = cur.next;
target = target.next;
}
return true;
}
}