LeetCode_234. Palindrome Linked List

題目描述:
在這裏插入圖片描述
思路1:申請一個vector,把鏈表中的元素都複製到vector中,然後用雙指針從兩端向中間比較

/**
 * 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) {
        vector<int> copy;
        ListNode* p=head;
        while(p){
            copy.push_back(p->val);
            p=p->next;
        }
        int n=copy.size();
        int i=0,j=n-1;
        while(i<j){
            if(copy[i]==copy[j]){
                i++;
                j--;
            }else{
                return false;
            }
        }
        return true;
    }
};
/**
 * 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) {
        if(head==NULL||head->next==NULL)//空鏈表或者一個節點的鏈表
            return true;
        return ISPAL(head);
    }
    bool ISPAL(ListNode* head){
        ListNode* fast,*slow;
        fast=slow=head;
        //這種循環方式保證了slow是中間的節點或者是中間的前一個節點
        while(fast->next&&fast->next->next){
            slow=slow->next;
            fast=fast->next->next;
        }
        slow->next=reverse(slow->next);
        slow=slow->next;
        while(slow){
            if(head->val!=slow->val)
                return false;
            head=head->next;
            slow=slow->next;
        }
        return true;
    }
    ListNode* reverse(ListNode* &head){
        ListNode* pre=head;
        ListNode* cur=pre->next;
        ListNode* p;
        while(cur){
            if(pre==head)
                pre->next=NULL;
            p=cur->next;
            cur->next=pre;
            pre=cur;
            cur=p;
        }
        return pre;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章