【LeetCode】234. Palindrome Linked List

来源:互联网 发布:淘宝店侦探怎么使用 编辑:程序博客网 时间:2024/05/29 02:38

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?

【思路一】将list反转到新list,后一一进行比较。

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public:    ListNode* reverse(ListNode* head)    {        ListNode* ptr = NULL;        while(head)        {            ListNode* tmp = new ListNode(head->val);            tmp->next = ptr;            ptr = tmp;            head = head->next;        }        return ptr;    };    bool isPalindrome(ListNode* head) {        if(head == NULL) return true;        ListNode* rev = reverse(head);        while(head)        {            if(rev->val != head->val)             return false;            else            {                rev =rev->next;                head = head->next;            }        }        return true;    }};

【思路二】将链表元素装入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) {        if(head==NULL) return true;        vector<int> ve;        while(head)        {            ve.push_back(head->val);            head = head->next;        }        for(int i =0, j= ve.size()-1; i<j;i++,j--)        {            if(ve[i]!=ve[j])                return false;        }        return true;    }};


0 0
原创粉丝点击