# 力扣234_回文链表

class Solution {
public boolean isPalindrome(ListNode head) {
//辅助数组部分 把链表的值全部存入数组
List<Integer> list = new ArrayList<>();
ListNode p = head;
while(p != null) {
list.add(p.val);
p = p.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;
}
}

void traverse(TreeNode root) {
traverse(root.left);
traverse(root.right);
// 后序遍历代码
}

/* 倒序打印单链表中的元素值 */
void traverse(ListNode head) {
if (head == null) return;
traverse(head.next);
// 后序遍历代码
print(head.val);
}

class Solution {
ListNode left;
public boolean isPalindrome(ListNode head) {
left = head;
return traverse(head);

}

public boolean traverse(ListNode right) {
if(right == null) return true;
boolean res = traverse(right.next);
res = res && (left.val == right.val);
left = left.next;
return res;
}
}

//使用快慢指针找到中间值
ListNode slow = head;
ListNode fast = head;
while(fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
//如果是奇数链表 那么中间值不参与比较
if(fast!=null) slow = slow.next;

ListNode left = head;
ListNode right = reverseList(slow);

while(right != null) {
if(left.val != right.val){
return false;
}
left = left.next;
right = right.next;
}
return true;

class Solution {
public boolean isPalindrome(ListNode head) {
//使用快慢指针找到中间值
ListNode slow = head;
ListNode fast = head;
while(fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
//如果是奇数链表 那么中间值不参与比较
if(fast!=null) slow = slow.next;

//开始比较
ListNode left = head;
ListNode right = reverseList(slow);
while(right != null) {
if(left.val != right.val){
return false;
}
left = left.next;
right = right.next;
}
return true;
}

public ListNode reverseList(ListNode head) {
if(head == null) return null;
if(head.next==null) return head;
ListNode last = reverseList(head.next);
head.next.next = head;
head.next = null;
return last;
}

}

05-12 173

06-10 3194
01-29 74
04-02 1028
08-19 40
09-09 98
03-03 32
11-29 72
04-03 148
11-24 58
03-18 59
06-21 2
07-09 1615
©️2020 CSDN 皮肤主题: 1024 设计师:白松林