原题出处:https://leetcode.cn/leetbook/read/top-interview-questions-easy/xnv1oc/
解法一:
/**
* 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) {
ListNode fast = head,slow = head;
while (fast != null && fast.next != null) {
fast = fast.next.next;
slow = slow.next;
}
if (fast != null) {
slow = slow.next;
}
slow = reserse(slow);
while (slow != null) {
if (head.val != slow.val) {
return false;
}
slow = slow.next;
head = head.next;
}
return true;
}
private ListNode reserse(ListNode head) {
ListNode result = null;
while (head != null) {
ListNode tmp = head.next;
head.next = result;
result = head;
head = tmp;
}
return result;
}
}
思路:首先定义一个快慢指针,慢指针走一步,块指针走两步,快指针或者快指针的下一个引用为null时,则表示快指针已经不能在移动了,而慢指针这个时候应该恰好在链表的中间位置,不过还有一个可能就是链表的长度为基数,这个时候,就需要校验块指针是不是为null,如果不为null则表示链表的长度为奇数,慢指针需要多移动一个位置,然后我们在反转慢指针的链表,在通过慢指针和原来的链表进行对比,如果每一个元素都相等就表示链表是回文链表,否则就不是回文链表。
解法二:
/**
* 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) {
if (head == null) {
return false;
}
ListNode tmp = head;
Stack<Integer> stack = new Stack();
int len = 0;
while (tmp != null) {
stack.push(tmp.val);
tmp = tmp.next;
len++;
}
len = len >> 1;
while (len-- >= 0) {
if (head.val != stack.pop()) {
return false;
}
head = head.next;
}
return true;
}
}
思路:使用栈这种数据结构来完成,首先将链表数据存入到栈中,根据栈的后进先出的性质,我们就能够从后开始遍历链表元素,然后再和原链表进行对比如果所有元素都相同则返回true即可,否则返回false。、
解法三:
/**
* 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 {
ListNode temp = null;
public boolean isPalindrome(ListNode head) {
temp = head;
return check(head);
}
private boolean check(ListNode head) {
if (head == null) {
return true;
}
boolean isCheck = check(head.next) && (temp.val == head.val);
temp = temp.next;
return isCheck;
}
}
思路:通过递归从后开始遍历元素,然后与原链表的从头遍历的元素进行比较即可。
private void printListNode(ListNode head) {
if (head == null)
return;
printListNode(head.next);
System.out.println(head.val);
}