题目:
Given a singly linked list, determine if it is a palindrome.
Example 1:
Input: 1->2 Output: false
Example 2:
Input: 1->2->2->1 Output: true
Follow up:
Could you do it in O(n) time and O(1) space?
这道题是要求一个给定的链表是否为回文列表(然后满脑子513orz),刚开始想到的办法就是reverse整个链表然后判断是否相等,但是这样会使用O(n)的空间,看了discussion发现可以直接reverse后半部分链表,让快慢指针分别走两步和走一步,找到链表的中间值,再把慢指针后面的给反转一下,然后代码就很快写出来了。在reverse的时候一不小心还return错了以后一定要注意,写isPal的时候注意中间处理的细节,其他好像就没什么了。时间复杂度O(n),24ms,67.11%,空间复杂度O(1),12.9M,43.1%(虽然看到有人在讨论这把原始输入给改掉了行不行但是我觉得不影响)。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
bool isPalindrome(ListNode* head) {
if (!head || !head->next) {
return true;
}
ListNode* slow = head;
ListNode* fast = head;
while (fast->next && fast->next->next) {
fast = fast->next->next;
slow = slow->next;
}
slow->next = reverse(slow->next);
fast = head;
slow = slow->next;
while (slow) {
if (slow->val != fast->val) {
return false;
}
slow = slow->next;
fast = fast->next;
}
return true;
}
ListNode* reverse(ListNode* head) {
ListNode* curr = head;
ListNode* prev = NULL;
while (curr) {
ListNode* next = curr->next;
curr->next = prev;
prev = curr;
curr = next;
}
return prev;
}
};
另外看到discussion还有一种用递归做的,很巧妙,但是懒得看了,贴个链接:https://leetcode.com/problems/palindrome-linked-list/discuss/64490/My-easy-understand-C%2B%2B-solution
来源:https://blog.csdn.net/qq_37333947/article/details/100827147