Leetcode ☞ 234. Palindrome Linked List

234. Palindrome Linked List

My Submissions
Question
Total Accepted: 40299  Total Submissions: 147797  Difficulty: Easy

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?









我的AC:(14ms,最快一批,击败25%)

bool isPalindrome(struct ListNode* head) {
    if (!head || !head->next) return true;//不加就runtime error
    
    struct ListNode *fast, *slow, *mid;
    fast = slow = head;
    while(fast->next && fast->next->next){
        fast = fast->next->next;
        slow = slow->next;
    }
    mid = slow->next;
    //[1,2,3,4]结束时,fast为3,slow为2【mid为3,正确】;[1,2,3,4,5]结束时,fast为5,slow为3【mid为4,正确】。
    //所以循环的条件一个是fast->next,另一个是fast->next->next而非fast。
    //不然,[1,2,3,4]结束时,fast为NULL,slow为3【mid为4,错误】;[1,2,3,4,5]结束时,fast为5,slow为3【mid为4,正确】。
    struct ListNode *p, *p1, *p2;
    p2 = mid;
    p1 = NULL;
    while(p2){
        p = p2->next;
        p2->next = p1;
        p1 = p2;
        p2 = p;
    }
    mid = p1;//此时原链表的后半部反转完成,接下来对前/后半部逐个对比。
    while(mid){
        if(mid->val != head->val)
            return false;
        mid = mid->next;
        head = head->next;
    }
    return true;
}
思路:

1、快慢指针找到中位数

2、反转后半部分

3、将head跟mid逐个对比


一定别忘if (!head || !head->next) return true;  !!!!


附找中位数代码(快慢指针):

struct ListNode *fast, *slow;  
fast = slow = head;  
if (!head || !head->next) return head;  
  
while (fast&&slow)  
{  
  if (fast->next==NULL)  
      return slow ->data;  
  else if (fast->next!= NULL && fast->next->next== NULL)  
      return (slow ->data + slow ->next->data)/2;  
  else{  
      fast= fast->next->next;  
      slow = slow ->next;  
  }  
}  























你可能感兴趣的:(Leetcode ☞ 234. Palindrome Linked List)