玩物丧志了这么久 ,,,,也该做道题活动一下脑子啦。。。
leetcode 234. Palindrome Linked List
Given a singly linked list, determine if it is a palindrome.( O(n) time and O(1) space)
我的想法: 先遍历一遍,把value放到栈里,利用栈的特性,对比栈里的值和linklist的值
class Solution {
public:
bool isPalindrome(ListNode* head) {
ListNode *begin=head;
stack<int> value;
while(begin!= NULL)
{
value.push(begin->val);
begin=begin->next;
}
begin=head;
while(begin!=NULL && !value.empty())
{
if(begin->val!= value.top()) break;
else
{
begin=begin->next;
value.pop();
}
}
if(begin!=NULL || !value.empty() ) return false;
else return true;
}
};
之后看到论坛里面的另外一种做法,首先遍历linklist 找到中间值 ,顺便把前半段的值逆序,接着 从头开始比较前半段和后半段的值,空间复杂度降低了不少呀 !!!!!!!!!!
class Solution {
public:
bool isPalindrome(ListNode* head) {
if( head==NULL || head->next==NULL ) return true;
// list has at least two nodes
ListNode *pre = NULL, *pfirst, *psecond;
auto px1 = head, px2 = head;
// traversal 1: reverse the first half and get pfirst&psecond in position
while(true) {
px2 = px2->next->next; // move px2 forward
pfirst = px1; px1 = px1->next;// move px1 forward
pfirst->next = pre; // point curent next back
if( px2 == NULL ) { // 2n Nodes
psecond = px1; break;
} else if( px2->next == NULL ) { // 2n+1 Nodes
psecond = px1->next; break;
}
pre = pfirst;
}
// traversal 2: check node values
while( pfirst!=NULL ) {
if( pfirst->val != psecond->val ) return false;
pfirst = pfirst->next; psecond = psecond->next;
}
return true;
}
};