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?
/**
* 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) {
ListNode[] ll = reverseHalf(head);
ListNode l1 = ll[0];
ListNode l2 = ll[1];
while(null != l1) {
if(l1.val != l2.val) {
return false;
}
l1 = l1.next;
l2 = l2.next;
}
return true;
}
private ListNode[] reverseHalf(ListNode head) {
ListNode[] ll = {null, null};
ListNode fast=head, slow=head, pre=null;
ListNode ph = new ListNode(0);
while(null != fast && null != fast.next) {
pre = slow;
slow = slow.next;
fast = fast.next.next;
pre.next = ph.next;
ph.next = pre;
}
if(null != pre) {
ll[0] = ph.next;;
if(null != fast) {
ll[1] = slow.next;;
} else {
ll[1] = slow;
}
}
return ll;
}
}
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
bool isPalindrome(ListNode* head) {
ListNode *l1=NULL, *l2=NULL;
reverseHalf(head, l1, l2);
while(l1) {
if(l1->val != l2->val) {
return false;
}
l1 = l1->next;
l2 = l2->next;
}
return true;
}
void reverseHalf(ListNode* head, ListNode* &l1, ListNode* &l2) {
ListNode *fast=head, *slow=head, *pre=NULL;
ListNode *ph = new ListNode(0);
while(fast && fast->next) {
pre = slow;
slow = slow->next;
fast = fast->next->next;
pre->next = ph->next;
ph->next = pre;
}
if(pre) {
l1 = ph->next;;
if(fast) {
l2 = slow->next;;
} else {
l2 = slow;
}
}
delete ph;
}
};
本文介绍了一种O(n)时间复杂度和O(1)空间复杂度的算法来判断单链表是否为回文串。通过反转链表的一半并比较两部分元素的方式实现。
507

被折叠的 条评论
为什么被折叠?



