Leetcode Palindrome Linked List 234

来源:互联网 发布:pre软件c4埋雷 编辑:程序博客网 时间:2024/05/17 15:41

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?

Subscribe to see which companies asked this question

题目链接

最开始考虑的是用栈来保存,时间和空间复杂度达到o(n)

/** * 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) return true;        int cnt=0;        ListNode* p = head;        while(p){            cnt++;            p=p->next;        }        if(cnt==1) return true;        stack<int> s;        p = head;        int tmpcnt=0;        while(p){            tmpcnt++;            if(tmpcnt==cnt/2) {                s.push(p->val);                break;            }            else{                s.push(p->val);            }            p=p->next;        }        if(cnt%2) {            p=p->next->next;        }        else p=p->next;        while(p){            if(p->val==s.top()){                p=p->next;                s.pop();            }            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 {private:    ListNode* he;public:    bool isPalindrome(ListNode* head) {        if(head==NULL || head->next==NULL) return true;        else{            he=head;            return judge(he);        }    }    bool judge(ListNode* h){        if(h==NULL) return true;        if(!judge(h->next)) return false;        if(he->val!=h->val) return false;        else{            he=he->next;            return true;        }    }};
0 0
原创粉丝点击