234. Palindrome Linked List。

来源:互联网 发布:mac outlook windows 编辑:程序博客网 时间:2024/06/14 15:06

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?


判断这个链表是不是回文,我的思路就是先找到链表的中间值,在找的过程中将前半段的数据放在栈中,然后找到中间之后,在分别从栈中出栈,然后和后半部分进行比较,如果中间出现不相等的数据就返回false,否则到最后返回true即可。

#include <iostream>#include <stack>using namespace std;struct ListNode {    int val;    ListNode *next;    ListNode(int x) : val(x), next(NULL) {}};class Solution {public:    bool isPalindrome(ListNode* head) {        stack<int> halfValues;//使用一个栈来保存链表前半边的节点.        ListNode* fast = head;        ListNode* slow = head;        if(!head) {            return true;        }        while(fast&&fast->next) {//使用快慢指针找到链表中点            fast = fast->next->next;            halfValues.push(slow->val);            slow = slow->next;        }        if(fast) {//fast指向不为空说明为奇数,此时不需要比较最中间的那个数值            slow = slow->next;        }        while(slow) {//不为空则遍历            if(slow->val != halfValues.top()) {                return false;            } else {                halfValues.pop();                slow = slow->next;            }        }        return true;    }};int main() {    Solution s;    ListNode node1(1);    ListNode node2(2);    ListNode node3(2);    ListNode node4(1);    node1.next = &node2;    node2.next = &node3;    node3.next = &node4;    cout << s.isPalindrome(&node1);}
原创粉丝点击