[Lintcode Medium] Palindrome Linked List

Source: Internet
Author: User
Tags lintcode

Palindrome Linked List

Implement a function to check if a linked list is a palindrome.

Example

Given 1->2->1 , return True

Challenge

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

////

1\find out the medium index of Linked list

2\ reverse the right part of linked list in place

3\compare their value;

/*** Definition for singly-linked list. * public class ListNode {* int val; * ListNode Next; * ListNode (int X) {val = x;}}*/ Public classSolution {/**     * @paramhead a ListNode *@returna Boolean*/     Public BooleanIspalindrome (ListNode head) {//Write Your code here        if(head==NULL|| head.next==NULL)return true; if(head.next.next==NULL)        {            if(head.val==head.next.val)return true; Else return false; } ListNode Fast=Head; ListNode Slow=Head;  while(fast.next!=NULL&& fast.next.next!=NULL) {Fast=Fast.next.next; Slow=Slow.next; } ListNode head2=Slow.next; ListNode Pre=NULL; ListNode cur=head2; Slow.next=NULL;  while(cur!=NULL) {ListNode next=Cur.next; Cur.next=Pre; Pre=cur; Cur=Next; } head2=Pre; ListNode P=Head; ListNode Q=head2;  while(q!=NULL)        {            if(p.val==q.val) {p=P.next; Q=Q.next; }            Else             return false; }        return true; }

[Lintcode Medium] 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.