//法一:用空间换 自己的sb方法
public boolean isPalindrome(ListNode head) {
int count = 0;
ListNode h = head;
while(h!=null){
count++;
h = h.next;
}
h = head;
int newC = 0,i = 0,num;
int[] node;
if(count%2 ==1){
num = (count/2)+1;
node = new int[num];
num = num-1;
}
else{
num = count/2;
node = new int[num];
}
while(h!=null){
if(newC >= num){
node[i++] = h.val;
}
newC++;
h = h.next;
}
h = head;
for( i = node.length-1;i>=0;i--){
if(h.val != node[i]) return false;
h = h.next;
}
return true;
}
//答案的动态数组
public boolean isPalindrome(ListNode head) {
List<Integer> num = new ArrayList<>();
ListNode h = head;
while(h!=null){
num.add(h.val);
h = h.next;
}
int p = 0,q = num.size()-1;
while(p<q){
if(!num.get(p).equals(num.get(q))) return false;
p++;q--;
}
return true;
}
//递归 妙啊
ListNode h;
public boolean isPalindrome(ListNode head) {
h = head;
return recur(head);
}
private boolean recur(ListNode head) {
if ( head != null) {
if (!recur( head.next)) {
return false;
}
if ( head.val != h.val) {
return false;
}
h =h.next;
}
return true;
}
//法三:把后半段反转然后快慢指针对比
public boolean isPalindrome(ListNode head) {
if (head == null) {
return true;
}
// 找到前半部分链表的尾节点并反转后半部分链表
ListNode firstHalfEnd = endOfFirstHalf(head);
ListNode secondHalfStart = reverseList(firstHalfEnd.next);
// 判断是否回文
ListNode p1 = head;
ListNode p2 = secondHalfStart;
boolean result = true;
while (result && p2 != null) {
if (p1.val != p2.val) {
result = false;
}
p1 = p1.next;
p2 = p2.next;
}
// 还原链表并返回结果
firstHalfEnd.next = reverseList(secondHalfStart);
return result;
}
private ListNode reverseList(ListNode head) {
ListNode prev = null;
ListNode curr = head;
while (curr != null) {
ListNode nextTemp = curr.next;
curr.next = prev;
prev = curr;
curr = nextTemp;
}
return prev;
}
private ListNode endOfFirstHalf(ListNode head) {
ListNode fast = head;
ListNode slow = head;
while (fast.next != null && fast.next.next != null) {
fast = fast.next.next;
slow = slow.next;
}
return slow;
}
回文链表
最新推荐文章于 2024-08-25 22:05:10 发布