问题描述:
请判断一个链表是否为回文链表。
示例 1:
输入: 1->2
输出: false
示例 2:
输入: 1->2->2->1
输出: true
进阶:
你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?
解决方案:
/**
* 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) {
vector<int> container;
if(head==NULL||head->next==NULL)
return true;
while(head!=NULL)
{
container.push_back(head->val);
head=head->next;
}
int size=container.size();
int clc=1;
for(int i=0,j=size-1;i<j;i++,j--)
{
if(container[i]==container[j])
continue;
else
clc=0;
}
if(clc==1)
return true;
else
return false;
}
};
总结:从更加适用的角度去思考用例,不能局限与某几个特定用例或不具有普遍性和推广性的用例,往往实现起来更高效。