您的位置:首页 > 其它

LeetCode 234 Palindrome Linked List

2016-04-08 01:12 393 查看
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?

思路:把链表分为前后两半部分,把后半部分链表进行反转,然后一起遍历前后两半部分链表,依次比较节点的值。

public boolean isPalindrome(ListNode head) {
if (head == null || head.next == null) return true;
ListNode fast = head, slow = head;//利用快慢指针,寻找中间节点
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
/*** Start:对链表后半部分进行反转 By yuanyuan.niu*/
ListNode pre = slow, cursor = slow.next;
while (cursor != null) {
ListNode tmp = cursor.next;
cursor.next = pre;
pre = cursor;
cursor = tmp;
}
slow.next = null;
/**end反转链表结束,pre作为链表后半部分反转后的头节点*/
while (pre != null) {
if (head.val != pre.val) return false;
pre = pre.next;
head = head.next;
}
return true;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: