题解 | #判断一个链表是否为回文结构#
判断一个链表是否为回文结构
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;
}
};