链表的回文结构
题目描述
对于一个链表,请设计一个时间复杂度为O(n),额外空间复杂度为O(1)的算法,判断其是否为回文结构。
给定一个链表的头指针A,请返回一个bool值,代表其是否为回文结构。保证链表长度小于等于900。
测试样例:
1->2->2->1
返回:true
解析:
首先创建一个傀儡结点,将原链表反转
然后``对比两个链表,相应位置是否相同
public class PalindromeList {
public boolean chkPalindrome(ListNode A)
{
// write code here
if (A == null || A.next == null)
{
return true;
}
ListNode B = new ListNode(A.val);
ListNode b = new ListNode(-1);
b.next = B;
ListNode head = A.next;
while (head != null)
{
ListNode temp = new ListNode(head.val);
temp.next = b.next;
b.next = temp;
head = head.next;
}
b = b.next;
while (b.next != null && A.next != null)
{
if (b.val != A.val)
{
return false;
}
b = b.next;
A = A.next;
}
return true;
}
}