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

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

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

相关推荐

头顶尖尖的程序员:我也是面了三四次才放平心态的。准备好自我介绍,不一定要背熟,可以记事本写下来读。全程控制语速,所有问题都先思考几秒,不要急着答,不要打断面试官说话。
点赞 评论 收藏
分享
评论
18
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务