234.回文链表
题目描述
请判断一个链表是否为回文链表。
示例 1:
输入: 1->2
输出: false
示例 2:
输入: 1->2->2->1
输出: true
进阶:
你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?
解法一:复制数组
class Solution {
public boolean isPalindrome(ListNode head) {
int[] arr = new int[50000];
int i=0;
while(head!=null){
arr[i++]=head.val;
head=head.next;
}
int lo=0,hi=i-1;
while(lo<hi){
if(arr[lo++]!=arr[hi--]) return false;
}
return true;
}
}
解法二:快慢指针
- 快慢指针分割回文前后部分
- 边扫描边边转换前半部分链表方向
1->2->2->1
1<-2 2->1
class Solution {
public boolean isPalindrome(ListNode head) {
if(head==null||head.next==null) return true;
ListNode slow = head,fast = head;
ListNode pre = null,prepre = null;
//边扫描分割,边转换前半段节点方向
while(fast!=null&&fast.next!=null){
pre =slow;
slow=slow.next;
fast=fast.next.next;
pre.next = prepre;
prepre = pre;
}
//若为奇数,则跳过中间节点,再判断回文
if(fast!=null) slow=slow.next;
while(slow!=null||pre!=null){
if(slow.val!=pre.val) return false;
slow=slow.next;
pre=pre.next;
}
return true;
}
}
解法三:栈(代码略)
存入栈后利用栈后入先出的特点,将弹出的栈逐个与链表比较。