2020年2月27日
LeetCode 234. Palindrome Linked List
C++, LeetCode, 算法, 编程
0 Comments
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?
解析:
判断一个链表是不是回文链表,即链表首尾对称。并且follow up中指出空间复杂度为O(n),时间复杂度为O(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 == NULL || head->next == NULL)
return true;
ListNode *slow =head, *fast = head;
while(fast->next && fast->next->next)//快慢指针找到链表中间节点
{
slow = slow->next;
fast = fast->next->next;
}
ListNode* pre = NULL, *next = NULL;
ListNode* temp = slow->next;
while(temp)//后半部分链表逆序
{
next = temp->next;
temp->next = pre;
pre = temp;
temp = next;
}
while(pre)//比较两个链表对应元素是否相等
{
if(pre->val != head->val)
return false;
pre=pre->next;
head = head->next;
}
return true;
}
};