回文链表
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?
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public boolean isPalindrome(ListNode head) {
// 使用快慢指针
ListNode fast = head;
ListNode slow = head;
// 快指针每次都比慢指针多走一步,当快指针到尾节点,刚好慢指针走到中间
while(fast!=null&&fast.next!=null)
{
fast = fast.next.next;
slow = slow.next;
}
// 从中开始的慢指针进行逆置,
ListNode cur = slow,prv = null,temp=null;
while(cur!=null)
{
temp = cur.next;
cur.next = prv;
prv = cur;
cur = temp;
}
while(prv!=null)
{
if(prv.val!=head.val)
return false;
prv = prv.next;
head =head.next;
}
return true;
}
}