回文链表

1.题目

请判断一个链表是否为回文链表。

示例:

输入: 1->2
输出: false

示例 2:

1
2
输入: 1->2->2->1
输出: true

2.分析

使用递归,递归的归刚好反向的,就回溯的过程中从前往后对比。

3.代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
/**
* 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 flag = check(head.next)&&(head.val==temp.val);
temp = temp.next;
return flag;
}
}