題目描述:
請判斷一個鏈表是否爲迴文鏈表。
示例 1:
輸入: 1->2 輸出: false
示例 2:
輸入: 1->2->2->1 輸出: true
代碼:
/**
* 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) {
int len=0;
vector<int>node;
ListNode *re_head=head,rever_head;
while(re_head!=NULL)
{
len++;
node.push_back(re_head->val);
re_head=re_head->next;
}
int mid_pre,mid_las;
mid_las=(len+1)/2;
mid_pre=(len%2)==0?mid_las-1:mid_las-2;
while(mid_las<=(len-1)||mid_pre>=0)
{
if(node[mid_pre]!=node[mid_las])
return false;
mid_las++;
mid_pre--;
}
return true;
}
};