目录
一、思路
二、代码
一、思路
找到中间节点
后半部分逆置链表
定义两个指针,一个从头开始出发
一个从中间位置开始出发
但是注意:链表个数可能是奇数或者偶数,需要注意中间节点的计算
二、代码
struct ListNode* reverseList(struct ListNode* head) {if(head == NULL){return NULL;}struct ListNode *prev = NULL,*cur = head, *next = cur->next;while(next){if(prev == NULL){cur->next = NULL;}else{cur->next = prev;}prev = cur;cur = next;next = next->next;}cur->next = prev;return cur;
}
#include <asm-generic/errno.h>
class PalindromeList {
public:bool chkPalindrome(ListNode* A) {// write code here//找中间节点struct ListNode *slow = A, *fast = A;while(fast && fast->next){slow = slow->next;fast = fast->next->next;}struct ListNode *mid = slow;struct ListNode *rhead = reverseList(slow);//比较struct ListNode *begin = A;while(begin && mid){if(begin->val != rhead->val)return false;begin = begin->next;mid = mid->next;}return true;}
};