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?
Subscribe to see which companies asked this question
/**
* 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) {
if(head==NULL || head->next==NULL)
return true;
ListNode *fast = head;
ListNode *slow = head;
stack<int> s;
s.push(head->val);
while(fast->next && fast->next->next)
{
fast = fast->next->next;
slow = slow->next;
s.push(slow->val);
}
if(!fast->next)
s.pop();
while(slow->next)
{
slow = slow->next;
int tmp = s.top();
s.pop();
if(tmp != slow->val)
return false;
}
return true;
}
};
本文介绍了一种使用栈辅助的O(n)时间复杂度和O(1)额外空间复杂度的方法来判断单链表是否为回文结构。通过快慢指针技巧找到链表中点,并利用栈保存前半部分链表节点值,与后半部分进行对比。
1248

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



