描述

给定一个链表,请判断该链表是否为回文结构。

整体思路:

创建string字符串,将链表中数据已字符形式逐个存入字符串中;再从头和尾分别同时遍历,若出现“从头数起第x个字符与从尾数起第x个字符不同”,则返回false;否则返回true
代码如下:
class Solution {
public:
    bool isPail(ListNode* head) {
        if(head->next==NULL) return true;
        string str;
        while(head)
        {
            str+=(head->val+'0');
            head=head->next;
        }
        int i=0,j=str.size()-1;
        while(i<j)
            if(str[i++]!=str[j--])
                return false;
        return true;
    }
};