题解 | 判断一个链表是否为回文结构
判断一个链表是否为回文结构
https://www.nowcoder.com/practice/3fed228444e740c8be66232ce8b87c2f
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) : val(x), next(nullptr) {}
* };
*/
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param head ListNode类 the head
* @return bool布尔型
*/
ListNode* ReverseList(ListNode* head) {//面试第一题,反转链表,前面已有不再详赘
// write code here
ListNode *pre=nullptr;
ListNode *cur=head;
while(cur){
ListNode *nxt=cur->next;
cur->next=pre;
pre=cur;
cur=nxt;
}
return pre;
}
bool isPail(ListNode* head) {
// write code here
if(!head) return true;//若链表为空,肯定回文
ListNode* p=head;
ListNode* q=head;
while(q->next!=nullptr&&q->next->next!=nullptr){//找到中间结点,
p=p->next;
q=q->next->next;
}
ListNode* m=p->next;//奇数的中间结点为p,偶数的中间为p和p->next的中间,后半链表都从从p->next开始
m=ReverseList(m);//更新后半部分链表,使其反转,记得再次令m等于Reverse更新指针
while(m&&head){//while(m) 应改为 while(m && head),避免 head 先遍历完导致空指针访
if(head->val!=m->val){//比较的是节点值而非地址
return false;
}
head=head->next;//依次遍历
m=m->next;
}
return true;
}
};
阿里云成长空间 786人发布