回文链表
请判断一个链表是否为回文链表。
示例 1:
输入: 1->2
输出: false
示例 2:
输入: 1->2->2->1
输出: true
分析
没有想到空间O(1)的算法,不过可以满足O(n)时间复杂度。
设置快慢两个指针遍历链表,并逆序记录前半段节点的值,与后半段节点顺次对比。
代码
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public boolean isPalindrome(ListNode head) {
if(head == null || head.next == null){
return true;
}
LinkedList<Integer> preList = new LinkedList<>();
ListNode slow = head;
ListNode fast = head;
preList.add(slow.val);
//快慢指针,遍历到中点位置,逆序记录前半段节点值
while(fast.next!=null && fast.next.next != null){
slow = slow.next;
fast = fast.next.next;
preList.add(0,slow.val);
}
if(fast.next!=null){
slow = slow.next;
}
for(int i=0;slow!=null;i++,slow=slow.next){
if(preList.get(i)!=slow.val){
return false;
}
}
return true;
}
}