Topic:
Given a singly linked list, determine if it is a palindrome.
Follow up:
Could do it in O (n) time and O (1) space?
Question answer: In the title, it is necessary to solve the problem in the time complexity of O (n) and the space Complexity of O (1), obviously, it is not advisable to copy and use stack to implement. The only idea that can be thought of is to reverse the list method.
The first half of the list is reversed and each node in the second half of the list is compared and the corresponding result is returned.
It is important to note that when the number of nodes in a linked list is different, different processing details are required.
The code is as follows:
/**
* 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;
Slownode = Slownode Next;
}
bool Node_num_even = true;
if (quicknode, next = NULL)//odd number of nodes
{
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 title: Palindrome Linked List