链表的回文结构_牛客题霸_牛客网 (nowcoder.com) (点击前面链接即可查看题目)
reverseList函数请参考:反转链表 - 力扣(LeetCode)C语言-CSDN博客
middleNode函数请参考:链表的中间结点 - 力扣(LeetCode)C语言-CSDN博客
链表:1->2->3->2->1
先找到中间结点, 也就是3,然后反转3->2->1,但是要注意标红的2仍旧指向3,
所以链表变成了1->2->3<-2<-1,就成了这样.
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};*/
class PalindromeList {
public:
struct ListNode* reverseList(struct ListNode* head) {
if (head == NULL)
return NULL;
else {
struct ListNode* oldhead = head;
struct ListNode* newhead = NULL;
while (oldhead) {
struct ListNode* nextnode = oldhead->next;
oldhead->next = newhead;
newhead = oldhead;
//迭代
oldhead = nextnode;
}
return newhead;
}
}
struct ListNode* middleNode(struct ListNode* head) {
struct ListNode* slow = head;
struct ListNode* fast = head;
//空指针
if (NULL == head) {
return NULL;
}
//一个结点
else if (NULL == head->next) {
return head;
}
//大于等于2个结点
else {
while (fast) {
if (NULL == fast->next) {
return slow;
}
slow = slow->next;
fast = fast->next->next;
}
return slow;
}
}
bool chkPalindrome(ListNode* A)
{
// write code here
ListNode* mid = middleNode(A);
ListNode* rmid = reverseList(mid);
while(rmid)
{
if(rmid->val != A->val)
{
return false;
}
else
{
rmid = rmid->next;
A = A->next;
}
}
return true;
}
};