Given a singly linked list, determine if it is a palindrome.
Example 1:
Input: 1->2 Output: false
Example 2:
Input: 1->2->2->1 Output: true
Follow up:
Could you do it in O(n) time and O(1) space?
判断单链表是不是回文串,首先写了一个反转链表函数reverseList,为了省时间在isPalindrome函数里面用双指针一快一慢让慢的走到中间的结点,然后只需要反转后面的一半结点,再跟前面的一半比较即可知道是不是回文串。
1 struct ListNode* reverseList(struct ListNode* head) { 2 if(!head) return NULL; 3 struct ListNode *prev=NULL,*next; 4 while(head){ 5 next=head->next; 6 head->next=prev; 7 prev=head; 8 head=next; 9 } 10 return prev; 11 } 12 bool isPalindrome(struct ListNode* head) { 13 if(!head || !head->next) return true; 14 15 struct ListNode *fast=head,*slow=head; 16 //如果fast->next或者fast->next->next少一个判断都会导致慢指针走多一步导致结果错误 17 while(fast && fast->next && fast->next->next){ 18 slow=slow->next; 19 fast=fast->next->next; 20 } 21 struct ListNode *mid=reverseList(slow->next); 22 slow->next=NULL; 23 while(mid){ 24 if(mid->val!=head->val) 25 return false; 26 mid=mid->next; 27 head=head->next; 28 } 29 return true; 30 }