标签:
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?
1、朴素方法
/** * Definition for singly-linked list. * struct ListNode { * int val; * struct ListNode *next; * }; */ struct ListNode* reverseList(struct ListNode* head) { if(head == NULL) return NULL; struct ListNode *nex = head->next, *pre = NULL; while(nex != NULL) { head->next = pre; pre = head; head = nex; nex = nex->next; } head->next = pre; return head; } bool isPalindrome(struct ListNode* head) { struct ListNode *tail = head; int n = 0,tmp = 0; if(head == NULL) return 1; while(tail != NULL) { tail = tail->next; n++; } for(int i = 0; i < n/2; i++) //通过不断的翻转链表来对比头尾的值 { tmp = head->val; head = head->next; tail = reverseList(head); if(tmp != tail->val) return 0; tail = tail->next; head = reverseList(tail); } return 1; }
2、网上答案:把后半段翻转,然后逐个对比值
bool isPalindrome(struct ListNode* head) { //如果链表为空或者仅有一个元素那么肯定是回文链表 if (!head || !head->next) { return true; } //快慢指针法,寻找链表中心 struct ListNode * slow, *fast; slow = fast = head; while (fast && fast->next) { //先检测fast是否为空,如果为空则fast->next不再运行,也就不会越界 slow = slow->next; //慢指针每次前进一格 fast = fast->next->next; //快指针每次前进两格 } if (fast) { slow = reverseList(slow->next); //如果fast不为空,则链表元素奇数个 }else{ slow = reverseList(slow); //如果fast为空,则链表元素偶数个 } while (slow) { if (head->val != slow->val) { return false; } slow = slow->next; head = head->next; } return true; }
标签:
原文地址:http://www.cnblogs.com/dylqt/p/4842262.html