题解 | #判断一个链表是否为回文结构#
判断一个链表是否为回文结构
http://www.nowcoder.com/practice/3fed228444e740c8be66232ce8b87c2f
题目描述:给定一个链表,请判断该链表是否为回文结构。
示例1
输入:[1]
返回值:true
示例2
输入:[2,1]
返回值:false
示例3
输入:[1,2,2,1]
返回值:true
思路:简单直接,将链表中所有数字放到数组中,遍历一般的数组,判断数组是否基于最中间元素轴对称即可。具体代码如下:
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
class Solution {
public:
/**
*
* @param head ListNode类 the head
* @return bool布尔型
*/
bool isPail(ListNode* head) {
// write code here
bool flag = true;
vector<int> res;
while(head!=NULL)
{
res.push_back(head->val);
head = head->next;
}
int n = res.size();
for(int i=0;i<n/2;i++)
if(res[i] != res[n-i-1])
{
flag = false;
break;
}
return flag;
}
};