您的位置:首页 > 其它

LeetCode:Palindrome Linked List

2015-08-04 10:59 423 查看
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?

回文链表即原链表与逆置链表相同,采用辅助栈的特点将链表逆置。(知道链表长度,可以将链表节点顺序映射到数组中,使用数组直接定位元素的特点也可以得到o(n)的时间复杂度)

/**
* 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;

stack<int> lstack;
//元素入栈
ListNode *p=head;

while(p)
{
lstack.push(p->val);
p=p->next;
}

//元素出栈与链表比较
p=head;
while(p)
{
if(p->val!=lstack.top())
return false;
lstack.pop();
p=p->next;

}

return true;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: