不算是好方法,只能说是这个地方的程序勉强能通过,我觉得应该会有更好的办法,但是目前想不到,所以可以过两天再过来看下
请判断一个链表是否为回文链表。
示例 1:
输入: 1->2
输出: false
示例 2:
输入: 1->2->2->1
输出: true
/**
* 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:
bool isPalindrome(ListNode* head) {
ListNode* tail=nullptr,*hr=head,*p;
if(head==nullptr) return true;
p=new ListNode(hr->val);
tail=p;
while(hr!=nullptr){
p=new ListNode(hr->val);
p->next=tail;
tail=p;
hr=hr->next;
}
while(head!=nullptr){
if(head->val!=tail->val){
return false;
}
head=head->next;
tail=tail->next;
}
return true;
}
};
京公网安备 11010502036488号