234. Palindrome Linked List

image.png

题解一:利用stack来判断回文,这里注意奇偶的处理,利用快慢指针找中点。

/**
 * 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;
        stack<int> ST;
        ListNode * slow = head;
        ListNode * fast = head->next;
        while(fast && fast->next){
            ST.push(slow->val);
            cout<<slow->val<<endl;
            fast = fast->next->next;
            slow= slow->next;
        }
        if(fast){
            ST.push(slow->val);
        }
        slow = slow->next;
        while(slow){
            int x = ST.top();
            ST.pop();
            if(slow->val != x){
                return false;
            }
            slow = slow->next;
        }
        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;
        }
        ListNode * fast = head->next;
        ListNode * slow = head;
        while(fast && fast->next){
            fast = fast->next->next;
            slow = slow->next;
        }
        if(fast){
            slow = slow->next;
        }
        ListNode * rhead = reverse(slow);
        ListNode * lcurr = head, * rcurr = rhead;
        while(rcurr){
            if(lcurr->val != rcurr->val){
                return false;
            }
            lcurr = lcurr->next;
            rcurr = rcurr->next;
        }
        return true;
        
    }
private:
    ListNode * reverse(ListNode *phead){
        ListNode * prev = NULL;
        ListNode * cur = phead;
        while(cur){
            ListNode *tmp = cur->next;
            cur->next = prev;
            prev = cur;
            cur = tmp;
        }
        return prev;
    }
};
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容