234. Palindrome Linked List, palindromelinked

Source: Internet
Author: User

234. Palindrome Linked List, palindromelinked

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

Follow up:
Cocould you do it in O (n) time and O (1) space?

 

1/** 2 * Definition for singly-linked list. 3 * struct ListNode {4 * int val; 5 * struct ListNode * next; 6 *}; 7 */8 bool isPalindrome (struct ListNode * head) {9 struct ListNode * q; // P step by step. q goes through two steps. q goes to the end, p goes to the intermediate node 10 struct ListNode * p; 11 struct ListNode * head2; 12 p = head; 13 q = head; 14 if (head = NULL) // The empty linked list is also considered as 15 return 1; 16 while (q-> next! = NULL) 17 {18 p = p-> next; 19 q = q-> next; 20 if (q-> next = NULL) 21 break; 22 q = q-> next; 23} 24 head2 = p; 25 while (p! = Q) // reverse 26 {27 head2 = head2-> next; 28 p-> next = q-> next; 29 q-> next = p; 30 p = head2; 31} 32 p = head; // traverse two linked lists from the beginning. 33 q = head2; 34 while (p! = NULL & q! = NULL) 35 {36 if (p-> val! = Q-> val) 37 break; 38 p = p-> next; 39 q = q-> next; 40 41} 42 if (NULL = p | NULL = q) // reach the end node, that is, the return link list 43 return 1; 44 return 0; 45}

 

Related Article

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.