文章目录
这题并不难,但是解法多样,所以作者觉得有必要写写!
题目
那上面例子来说: 就是链表的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;
}
}
附图
解法二 - 通过将链表节点的val值 存入 顺序表/数组 中, 通过数组下标进行对比。
代码
/**
* 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;
}
}