标签:
Given a singly linked list, determine if it is a palindrome.
Follow up:
Could you do it in O(n) time and O(1) space?
Subscribe to see which companies asked this question
Solution:
将数组后半段翻转,判断前后半段是否一致即可。
1 bool isPalindrome(ListNode* head) 2 { 3 if (!head || !head->next) 4 return true; 5 6 ListNode* fast = head; 7 ListNode* slow = head; 8 while (fast && fast->next) 9 { 10 fast = fast->next->next; 11 slow = slow->next; 12 } 13 14 if (fast) // odd nodes 15 { 16 slow->next = reverseList(slow->next); 17 slow = slow->next; 18 } 19 else 20 { 21 slow = reverseList(slow); 22 } 23 24 while (slow) 25 { 26 if (head->val != slow->val) 27 return false; 28 head = head->next; 29 slow = slow->next; 30 } 31 32 return true; 33 } 34 35 ListNode* reverseList(ListNode* head) 36 { 37 if (!head || !head->next) 38 return head; 39 40 ListNode* p = head, *q = p->next, *r = q->next; 41 while (r != NULL) 42 { 43 q->next = p; 44 p = q; 45 q = r; 46 r = r->next; 47 } 48 q->next = p; 49 head->next = NULL; 50 head = q; 51 52 return head; 53 }
[leetcode] 206.Palindrome Linked List
标签:
原文地址:http://www.cnblogs.com/ym65536/p/5487864.html