题解 | #判断一个链表是否为回文结构#
判断一个链表是否为回文结构
http://www.nowcoder.com/practice/3fed228444e740c8be66232ce8b87c2f
一、利用双指针
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
class Solution {
public:
/**
*
* @param head ListNode类 the head
* @return bool布尔型
*/
bool isPail(ListNode* head) {
// write code here
vector<int> nums;
while(head != NULL){
nums.push_back(head->val);
head = head->next;
}
int left = 0;
int right = nums.size()-1;
while(left <= right){
if(nums[left] != nums[right])
{
return false;
}
left++;
right--;
}
return true;
}
};
>
**二、栈**
``` /**
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
class Solution {
public:
/**
*
* @param head ListNode类 the head
* @return bool布尔型
*/
bool isPail(ListNode* head) {
// write code here
ListNode* p = head;
stack<int> s;
while(p){
s.push(p->val);
p = p->next;
}
p = head;
while(!s.empty()){
if(s.top() != p->val)
return false;
s.pop();
p = p->next;
}
return true;
}
};