Given a singly linked list, determine if it is a palindrome.
Follow up:
Could you do it in O(n) time and O(1) space?
判断链表是否是对称的。
分析:
1、采用快慢指针,找到中间节点
2、将后半段链表反转
3、对前后两半段链表进行判断
程序如下所示:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public boolean isPalindrome(ListNode head) {
if (head == null){
return true;
}
ListNode first = head;
ListNode slow = head, fast = head;
while (fast != null&&fast.next != null&&fast.next.next != null){
slow = slow.next;
fast = fast.next.next;
}
ListNode tmp = slow.next;
slow.next = null;
ListNode node = null;
while (tmp != null){
ListNode t = tmp.next;
tmp.next = node;
node = tmp;
tmp = t;
}
while (node != null&&first != null){
if (node.val != first.val){
return false;
}
node = node.next;
first = first.next;
}
return true;
}
}