题目:
Given the head
of a singly linked list, return true
if it is a palindrome.
Example 1:
Input: head = [1,2,2,1] Output: true
Example 2:
Input: head = [1,2] Output: false
Constraints:
- The number of nodes in the list is in the range
[1, 105]
. 0 <= Node.val <= 9
Follow up: Could you do it in O(n)
time and O(1)
space?
思路1:
很简单,先用容器把每个node存下来,然后对于容器使用两个pointer,一个从头到尾一个从尾到头,检查是否回文即可。但是要消耗空间复杂度。
代码1:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
//iterative
bool isPalindrome(ListNode* head) {
vector<int> record;
while(head)
{
record.push_back(head->val);
head=head->next;
}
for(int i=0,j=record.size()-1;i<=j;i++,j--)
{
if(record[i]!=record[j])
return false;
}
return true;
}
};
思路2:
理论上其实也是的空间复杂度,因为是递归的,其实消耗了栈空间。首先用一个额外的node来记录当前的位置。遍历List,如果当前node是空则返回true,说明我们到了尾部;之后记录下一个和当前是否回文,然后往下移一格即可。总的来说是一道比较老的题,思路想清楚了即可。
代码2:
class Solution {
public:
//recursive
ListNode* temp;
bool isPalindrome(ListNode* head)
{
temp=head;
return check(temp);
}
bool check(ListNode* cur)
{
if(!cur)
return true;
bool flag = check(cur->next) && cur->val==temp->val;
temp=temp->next;
return flag;
}
};