题解 | #判断一个链表是否为回文结构#

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

http://www.nowcoder.com/practice/3fed228444e740c8be66232ce8b87c2f

用字符串来比较

在遍历链表的同时,分别采用头插和尾插的方法构造2个字符串,然后比较这两个字符串是否相等即可。

代码如下:

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

class Solution {
public:
    /**
     * 
     * @param head ListNode类 the head
     * @return bool布尔型
     */
    bool isPail(ListNode* head) {
        // write code here
        ListNode* p = head;
        string str1;
        string str2;
        bool ret = true;
        while(p){
            str1 += (char)p->val;
            str2 = (char)p->val + str2;
            p = p->next;
        }
        return str1==str2;
    }
};
全部评论
不能使用 char {1,2000000,30000000,1}
点赞 回复 分享
发布于 2022-07-28 11:11

相关推荐

许愿ssp的咸鱼很不想泡池子:import python as pyhton
点赞 评论 收藏
分享
牛客鼠:校友你这简历基本无敌了,春招刷刷题去冲大厂
点赞 评论 收藏
分享
评论
18
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务