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}