那上面例子来说: 就是链表的val值, 从左往右看(1,2,2,1)和 从右往左看(1,2,2,1),都是一样的,就返回true , 否则返回 false。
先使用快慢指针,得到中间节点,然后反转 中间后半部分 链表节点,然后就是判断回文
class Solution {
public boolean isPalindrome(ListNode head) {
if(head == null){
return true;
}
ListNode fast = head;
ListNode slow = head;
while(fast!=null && fast.next != null){
fast = fast.next.next;
slow = slow.next;
}
ListNode cur = slow.next;
while(cur!=null){
ListNode curNext = cur.next;
cur.next = slow;
slow = cur;
cur = curNext;
}
while(head!=slow){
if(head.val != slow.val){
return false;
}
if(head.next == slow){
return true;
}
head = head.next;
slow = slow.next;
}
return true;
}
}
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode() {} * ListNode(int val) { this.val = val; } * ListNode(int val, ListNode next) { this.val = val; this.next = next; } * } */
class Solution {
public boolean isPalindrome(ListNode head) {
List<Integer> list = new ArrayList<>();
ListNode currentNode = head;
while(currentNode != null){
list.add(currentNode.val);
currentNode = currentNode.next;
}
int front = 0;
int back = list.size()-1;
while(front < back){
if(list.get(front) != list.get(back) ){
return false;
}
front++;
back--;
}
return true;
}
}
递归方法就是效率低了。
class Solution {
private ListNode frontPointer;
public boolean isPalindrome(ListNode head) {
frontPointer = head;
return recursive(head);
}
private boolean recursive(ListNode currentNode){
if(currentNode != null){
if(!recursive(currentNode.next)){
return false;
}
if(currentNode.val != frontPointer.val){
return false;
}
frontPointer =frontPointer.next;
}
return true;
}
}
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://blog.csdn.net/DarkAndGrey/article/details/122111676
内容来源于网络,如有侵权,请联系作者删除!