回文链表
题目
设计一种方式检查一个链表是否为回文链表。
样例
1->2->1 就是一个回文链表。
挑战
O(n)的时间和O(1)的额外空间。
题解
使用快慢指针找到链表的中点,然后以该节点为头节点进行反转,再从头进行双指针遍历判断。
如1->2->3->2->1->null,找到中间节点为3,对3->2->1->null进行翻转得到1->2->1->2->3->null,再用双指针分别指向两个1,进行遍历判断,直至结束或者发现值不相等的节点。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
/**
* @param head a ListNode
* @return a boolean
*/
public boolean isPalindrome(ListNode head) {
if (head == null || head.next == null)
{
return true;
}
ListNode low = head;
ListNode fast = head.next;
ListNode newHalfHead = null;
while (fast != null && fast.next != null && fast.next.next != null)
{
fast = fast.next.next;
low = low.next;
}
newHalfHead = reverse(low.next);
low.next = newHalfHead;
while (head != low.next)
{
if (head.val != newHalfHead.val)
{
return false;
}
head = head.next;
newHalfHead = newHalfHead.next;
}
return true;
}
private ListNode reverse(ListNode head)
{
ListNode pre = head;
ListNode p = head.next;
ListNode next = null;
while (p != null)
{
next = p.next;
p.next = pre;
pre = p;
p = next;
}
head.next = null;
return pre;
}
}
Last Update 2016.11.5