题解 | #判断一个链表是否为回文结构#
判断一个链表是否为回文结构
https://www.nowcoder.com/practice/3fed228444e740c8be66232ce8b87c2f
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
/**
*
* @param head ListNode类 the head
* @return bool布尔型
*/
bool isPail(struct ListNode* head ) {
// write code here
if(head->next==NULL) return true;
int arr[100001]={};
struct ListNode* tmp=head;
int count=0;
while(tmp!=NULL){
arr[count++]=tmp->val;
tmp=tmp->next;
}
int flag=0;
for(int i=0;i<count/2;i++){
if(arr[i]!=arr[count-i-1]){
flag=1;
break;
}
}
if(flag==0) return true;
else return false;
}
本题的几个思路:1.使用之前的链表翻转进行处理,这样只需要验证前后的一致性;
2.使用数组进行处理,由于可以随机查找,因此处理起来会更方便,但占用空间较大;
另外,这里的flag变量其实可以省略,当在循环中找到不满足直接可以return,因为这里并非要求找到一组满足的解,因此flag的存在就没有必要性。

