题目
请判断一个链表是否为回文链表。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
bool isPalindrome(struct ListNode* head) {
}
示例 1:
输入: 1->2
输出: false
示例 2:
输入: 1->2->2->1
输出: true
要求:
你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?
题解
思路:找到链表的中心点,将中心点后的链表做翻转,两个指针同时从头结点和中心点的 next 节点开始遍历,val值不一样则不是回文链表,都一样则是回文链表
note:用快慢指针找中心点,循环条件设为(fast->next != NULL && fast->next->next != NULL)时可以不考虑节点数的奇偶直接找到中心点。
bool isPalindrome(struct ListNode* head) {
if (head == NULL || head->next == NULL) return true;
struct ListNode *fast = head, *slow = head;
while (fast->next != NULL && fast->next->next != NULL) {
slow = slow->next;
fast = fast->next->next;
}
struct ListNode *last = slow->next, *temp;
while (last->next != NULL) {
temp = last->next;
last->next = temp->next;
temp->next = slow->next;
slow->next = temp;
}
while (slow->next != NULL) {
if (slow->next->val != head->val) return false;
head = head->next;
slow = slow->next;
}
return true;
}