标签:
题目:
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(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 * QuickNode = head;
ListNode * SlowNode = head;
while((QuickNode != NULL) && (QuickNode -> next != NULL) && (QuickNode -> next -> next != NULL))
{
QuickNode = QuickNode -> next -> next;
SlowNode = SlowNode -> next;
}
bool node_num_even = true;
if(QuickNode -> next == NULL) //奇数个节点
{
node_num_even = false;
}
ListNode *p = NULL;
ListNode *q = head;
ListNode *r = q -> next;
while(q != SlowNode)
{
q -> next = p;
p = q;
q = r;
r = q -> next;
}
q -> next = p;
if(!node_num_even)
{
q = q -> next;
}
while((q != NULL) && (r != NULL) && (q -> val == r -> val))
{
q = q -> next;
r = r -> next;
}
if((q == NULL) && (r == NULL))
return true;
else
return false;
}
};
Leetcode题目:Palindrome Linked List
标签:
原文地址:http://www.cnblogs.com/CodingGirl121/p/5443871.html