【Leetcode234】Palindrome Linked List

這裏用了三種方法:

list, stack,和快慢指針結合stack,前兩個方法速度都很慢,最後一個快了很多,代碼能力太差,有時間重寫一遍。

另外還有原地的o(1)的實現,reverse,還不會,太餓了。

參考:https://www.cnblogs.com/grandyang/p/4635425.html 

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    bool isPalindrome(ListNode* head) {
        // list<int> l;
        // // if(head == NULL) return false;
        // while(head != NULL){
        //     l.push_back(head->val);
        //     head = head->next;
        // }
        // while(l.size() > 1){
        //     if(l.front() != l.back())
        //         return false;
        //     else{
        //         l.pop_front();
        //         l.pop_back();
        //     }
        // }
        // return true;
        // if(head == NULL)
        //     return true;
        // stack<int> s;
        // ListNode* push_node = head;
        // ListNode* pop_node = head;
        // while(push_node != NULL){
        //     s.push(push_node->val);
        //     push_node = push_node->next;
        // }
        // while(!s.empty()){
        //     if(s.top() != pop_node->val)
        //         return false;
        //     else{
        //         s.pop();
        //         pop_node = pop_node->next;
        //     }
        // }
        // return true;
        //用快慢指針找中點,節省一半的時間
       if (head == NULL || head->next == NULL)
            return true;
        stack<int> s;
        ListNode *slow = head;
        ListNode *fast = head;
        while (fast->next && fast->next->next) {
            s.push(slow->val);
            slow = slow->next;
            fast = fast->next->next;
        }
        if (fast->next != NULL) {//如果不是最後一個節點,那麼總共有偶數個節點,stack的頂部是前一半的最後
            s.push(slow->val);
        }
        while (slow->next != NULL) {
            slow = slow->next;
            if (s.top() != slow->val)
                return false;
            else {
                s.pop();
            }
        }
        return true;
    }    
};

快慢指針:

a b c d e f 

      1    1

或者

a b c d e

      1    1

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章