Leetcode Palindrome Linked List

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?

题目意思:

  给定一个单链表,判断它是不是回文串

  进一步思考:

    你可以在O(n)时间复杂度和O(1)空间复杂度完成吗?

解题思路:

方法一:通过反转链表实现

  (1)使用快慢指针寻找链表中点

  (2)将链表的后半部分就地逆置

  (3)比较前后两半的元素是否一致

  (4)恢复原始链表的结构

方法二:通过递归实现

  (1)递归遍历链表到最后一个元素

  (2)如果第一个元素和最后一个元素相等,则递归回退,且第一个元素left=left->next

  (3)如果所有元素相等,则认为是回文串

源代码:

方法一:

 1 class Solution {
 2 public:
 3     bool isPalindrome(ListNode* head) {
 4         if(head == NULL || head->next == NULL ) return true;
 5         ListNode* fast = head, *slow = head;
 6         while(fast->next && fast->next->next){
 7             fast = fast->next->next;
 8             slow = slow->next;
 9         }
10         ListNode *p = slow->next, *second = NULL;
11         while(p){
12             ListNode* tmp = p->next;
13             p->next = second;
14             second = p;
15             p = tmp;
16         }
17         ListNode* p1 = head, *p2 = second;
18         while(p2 && p1->val == p2->val){
19             p1 = p1->next;
20             p2 = p2->next;
21         }
22         p = second; second = NULL;
23         while(p  ){
24             ListNode *tmp = p->next;
25             p->next = second;
26             second = p;
27             p = tmp;
28         }
29         return p2 == NULL ;
30     }
31 };

方法二:

 1 class Solution {
 2 public:
 3     bool isPalindrome_aux(ListNode** left, ListNode* right){
 4             if(right == NULL) return true;
 5             if(!isPalindrome_aux(left,right->next)) return false;
 6             bool res = (right->val == (*left)->val);
 7             *left = (*left)->next;
 8             return res;
 9         
10     }
11     bool isPalindrome(ListNode* head) {
12         return isPalindrome_aux(&head,head);
13     }
14 };

 

 

  

posted @ 2015-08-02 17:12  OpenSoucre  阅读(297)  评论(0编辑  收藏  举报