- 回文链表
请判断一个链表是否为回文链表。
示例 1:
输入: 1->2
输出: false
示例 2:
输入: 1->2->2->1
输出: true
进阶:
你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?
class Solution {
public boolean isPalindrome(ListNode head) {
ArrayList<Integer> list = new ArrayList<>();
while(head != null){
list.add(head.val);
head = head.next;
}
int len = list.size();
for(int i = 0; i < len/2; i++){
if(list.get(i).intValue() != list.get(len - 1 - i).intValue()) return false;
}
return true;
}
}
这里注意要用到intValue()方法,因为存在有的数组超过129,不能用等号来判断
2.递推法自己需要慢慢体会
class Solution {
ListNode front;
public boolean isPalindrome(ListNode head) {
front = head;
return recur(head);
}
boolean recur(ListNode now){
if(now != null){
if(recur(now.next) == false) return false;//这个产生递推
//如果成立,recur(now.next)也将返回true,注意
if(now.val != front.val) return false;//now运行到这里,其实在结尾的位置,恰好是从后往前
//先把所有的不成立情况一一列出来
front = front.next;//front也要随之移动
}
return true;
}
}
class Solution {
public boolean isPalindrome(ListNode head) {
if(head == null) return true;
ListNode mid = endOfFirstHalf(head);
ListNode newstart = reverseList(mid.next);
//先存着两个点的位置
ListNode p1 = head;
ListNode p2 = newstart;
boolean result = true;
while( p2 != null){//注意这里不能写p1,因为对于只有一个点的情况下
//p2= null,同时发现剩下的案例都不能通过了,直接就是runtime Exception
if(p1.val != p2.val){
result = false;
break;
}
p1 = p1.next;
p2 = p2.next;
}
//不管满足还是不满足,一律反转恢复
mid.next = reverseList(newstart);
return result;
}
private ListNode reverseList(ListNode head) {
ListNode n1, n2, n3;
n1 = null;
n2 = head;
n3 = null;
while(n2 != null){
n3 = n2.next;
n2.next = n1;
n1 = n2;
n2 = n3;
}
return n1;
}
private ListNode endOfFirstHalf(ListNode head) {
ListNode fast = head.next;
ListNode slow = head;
while (fast != null && fast.next != null) {
fast = fast.next.next;
slow = slow.next;
}
return slow;
}
}