LeetCode 234. Palindrome Linked List
Solution1:我的答案
一遍过,哈哈哈!
/**
* 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;//题目无明确要求,暂认为空指针是回文串
stack<struct ListNode*> temp_stack;
int num_listnode = 0;
struct ListNode *cur = head;
while (cur) {
num_listnode++;
cur = cur->next;
}
//把前半段链表装到栈里头
int i = 1; cur = head;
while (i <= num_listnode/2) {
temp_stack.push(cur);
cur = cur->next;
i++;
}
if (num_listnode % 2 == 1) cur = cur->next;
while (!temp_stack.empty()) {
if (cur->val != temp_stack.top()->val)
return false;
else {
cur = cur->next;
temp_stack.pop();
}
}
return true;
}
};