您的位置:首页 > 其它

[leetcode] 234.

2015-08-29 00:59 246 查看
题目:

Given a singly linked list, determine if it is a palindrome.

Follow up:

Could you do it in O(n) time and O(1) space?

题意:

给定一个单链表,确定它是否是回文的,即元素收尾对应相等。

思路:

因为需要O(1)的空间复杂度,O(n)的时间复杂度,我们采用快慢两个指针,取得链表的后半部分,将后半部分反转,然后将前后两个部分的元素一一对比。

代码如下:

/**
* 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* first = head, *second = head;
while (second != NULL && second->next != NULL && second->next->next!= NULL) {
first = first->next;
second = second->next->next;
}
second = reverse(first->next);//reverse the second part
first->next = NULL;
while (head != NULL && second != NULL) {
if (head->val != second->val)return false;
head = head->next;
second = second->next;
}
return true;
}
ListNode* reverse(ListNode* head) {
if (head == NULL || head->next == NULL)return head;
ListNode* h = head, *next;
head = head->next;
h->next = NULL;
while (head != NULL) {
next = head->next;
head->next = h;
h = head;
head = next;
}
return h;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: