[leetcode] 234. Palindrome Linked List

来源:互联网 发布:silence网络什么意思 编辑:程序博客网 时间:2024/06/05 05:56

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的中心node的坐标。同时使用一个stack,存储前半段node的数值。这里有一个地方要注意,当list长度是奇数时,slow正好停在正中心。当list长度是偶数时,需要将slow的当前值再push一次。

/** * 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 || !head->next) return true;        ListNode* slow = head, *fast = head;        stack<int> vals;                 while(fast->next && fast->next->next){            vals.push(slow->val);            slow = slow->next;             fast = fast->next->next;        }        if (fast->next) vals.push(slow->val);                while(slow->next){            if (slow->next->val!=vals.top()) return false;            else{                slow = slow->next;                vals.pop();            }        }                return true;            }};

解法二:

获得list中心还是一样,然后需要翻转后半段list。

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


0 0
原创粉丝点击