1. 程式人生 > >leetcode 234. 回文鏈表(Palindrome Linked List)

leetcode 234. 回文鏈表(Palindrome Linked List)

int false ref val pre struct while 回文 一個

目錄

  • 題目描述:
  • 示例 1:
  • 示例 2:
  • 進階:
  • 解法:

題目描述:

請判斷一個鏈表是否為回文鏈表。

示例 1:

    輸入: 1->2
    輸出: false

示例 2:

    輸入: 1->2->2->1
    輸出: true

進階:

你能否用 O(n) 時間復雜度和 O(1) 空間復雜度解決此題?

解法:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* reverse(ListNode* head){
        if(!head || !head->next){
            return head;
        }else{
            ListNode* cur = head, * nxt = head->next;
            head->next = NULL;
            while(nxt){
                cur = nxt;
                nxt = nxt->next;
                cur->next = head;
                head = cur;
            }
            return head;
        }
    }
    
    bool isPalindrome(ListNode* head) {
        if(!head || !head->next){
            return true;
        }else{
            int sz = 0;
            ListNode* cur = head;
            while(cur){
                sz++;
                cur = cur->next;
            }
            int half = (sz + 1)/2;
            cur = head;
            for(int i = 1; i < half; i++){
                cur = cur->next;
            }
            ListNode* rh = cur->next;
            cur->next = NULL;
            rh = reverse(rh);
            cur = head;
            while(cur && rh && cur->val == rh->val){
                cur = cur->next;
                rh = rh->next;
            }
            return rh == NULL;
        }
    }
};

leetcode 234. 回文鏈表(Palindrome Linked List)