题解 | #链表的回文结构#
链表的回文结构
https://www.nowcoder.com/practice/d281619e4b3e4a60a2cc66ea32855bfa
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};*/
class PalindromeList {
public:
struct ListNode* reverseList(struct ListNode* head) {
struct ListNode* cur = head;
struct ListNode* rhead = NULL;
while (cur) {
struct ListNode* next = cur->next;
// 头插
cur->next = rhead;
rhead = cur;
//迭代
cur = next;
}
return rhead;
}
struct ListNode* middleNode(struct ListNode* head) {
struct ListNode* fast = head, *slow = head;
while (fast && fast->next) {
slow = slow->next;
fast = fast->next->next;
}
return slow;
}
bool chkPalindrome(ListNode* head) {
// write code here
struct ListNode *mid = middleNode(head);
struct ListNode *rmid = reverseList(mid);
while (rmid)
{
if (rmid->val != head->val)
{
return false;
}
else
{
rmid = rmid->next;
head = head->next;
}
}
return true;
}
};
