
Problem Description:
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?
题目大意:
判断一个单向链表是否是回文的。
Solutions:
存下来每一个结点的值,判断是否是对称的即可。至于follow up,可以考虑反转后半个链表,然后挨个比对是否和前半部分相等即可。本文只给出第一种解法。
Code in C++:
/**
* 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> v;
while(head)
{
v.push_back(head->val);
head=head->next;
}
for(int i = 0;i< v.size()/2 ; i++)
if(v[i]!=v[v.size()-1-i]) return false;
return true;
}
};




近期评论