Leetcode title: Palindrome Linked List

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.