Given a singly linked list, determine if it is a palindrome.
Example 1:
Input: 1->2
Output: false
Example 2:
Input: 1->2->2->1
Output: true
Follow up:
Could you do it in O(n) time and O(1) space?
思路:
不能使用数组,因为空间复杂度不满足要求。只能用其他方法:
1.找到中间节点(快慢指针法)
2.后一半链表反转(头插法,没有创建头节点)
3.后一半链表和前一半链表节点一 一比较
代码:
class Solution {
public boolean isPalindrome(ListNode head) {
ListNode mid=getMiddleNode(head);
mid=reverse(mid);
while(mid!=null){
if(mid.val!=head.val)
return false;
mid=mid.next;
head=head.next;
}
return true;
}
public ListNode getMiddleNode(ListNode head){//快慢指针获取中间节点
ListNode fast=head,low=head;
while(fast!=null&&fast.next!=null){
fast=fast.next.next;
low=low.next;
}
if(fast==null)
return low;
else
return low.next;
}
public ListNode reverse(ListNode head){//反转链表
ListNode cur=head;
ListNode l1=null;
while(head!=null){
cur=cur.next;
head.next=l1;
l1=head;
head=cur;
}
return l1;
}
}