LeetCode *** 234. Palindrome Linked List

来源:互联网 发布:java开源门户网站 编辑:程序博客网 时间:2024/05/29 04:26

题目:

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?



分析:

如果要得到一个在中间的值,可以考虑一个走一步,一个走两步。


代码:

O(n)space

/** * 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;        vector<int> detail;                while(head){            detail.push_back(head->val);            head=head->next;        }                int len=detail.size();                for(int i=0;i<len/2;++i){            if(detail[i]!=detail[len-1-i])return false;        }                return true;            }};

O(1)space


/** * 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,*slow=head;                while(fast->next!=NULL&&fast->next->next!=NULL){            slow=slow->next;            fast=fast->next->next;        }                slow=reverse(slow->next);                while(slow!=NULL){            if(head->val!=slow->val)return false;            head=head->next;            slow=slow->next;        }        return true;            }        ListNode *reverse(ListNode *head){                ListNode *res=NULL;        ListNode *tmp=NULL;                while(head!=NULL){                      tmp=head->next;           head->next=res;           res=head;           head=tmp;        }                return res;    }};

0 0
原创粉丝点击