一、题目描述
对于一个链表,请设计一个时间复杂度为O(n),额外空间复杂度为O(1)的算法,判断其是否为回文结构。
给定一个链表的头指针A,请返回一个bool值,代表其是否为回文结构。保证链表长度小于等于900。
二、示例
测试样例:1->2->2->1
返回:true
三、实现
- 首先找到中间结点
- 将中间结点后半部分倒置
- 分别从头结点和尾结点向中间遍历,检测在达到中间时刻之间val的值是否都相等
struct ListNode* middleNode(struct ListNode* head) {
struct ListNode* slow = head, * fast = head;
while (fast && fast->next) {
slow = slow->next;
fast = fast->next->next;
}
return slow;
}
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;
}
typedef struct ListNode ListNode;
bool chkPalindrome(ListNode* phead) {
// write code here
struct ListNode* mid = middleNode(phead);
struct ListNode* rmid = reverseList(mid);
while (rmid) {
if (rmid->val != phead->val) {
return false;
}
else {
rmid = rmid->next;
phead = phead->next;
}
}
return true;
}
1263

被折叠的 条评论
为什么被折叠?



