牛客题霸 [判断一个链表是否为回文结构] C++题解/答案

判断一个链表是否为回文结构

题目描述

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

题解:

直接将链表内的数据存入string中,然后从两端开始向中间判断即可

代码:

/**
 * struct ListNode {
 *	int val;
 *	struct ListNode *next;
 * };
 */

class Solution {
public:
    /**
     * 
     * @param head ListNode类 the head
     * @return bool布尔型
     */
    bool isPail(ListNode* head) {
        // write code here
        string s = "";
        if(!head) return true;
        
        while(head)
        {
            s += (head->val + '0');
            head = head->next;
        }
        int i = 0, j = s.size() - 1;
        while(i < j)
        {
            if(s[i ++] != s[j --]) return false;
        }
        return true;
    }
};
posted @ 2020-11-07 00:03  回归梦想  阅读(117)  评论(0编辑  收藏  举报