https://leetcode-cn.com/problems/palindrome-linked-list/
请判断一个链表是否为回文链表。
示例1:
输入:1->2
输出:false
示例2:
输入:1->2->2->1
输出:true
“慢”指针:一次进一格
“快”指针:一次进两格
先找到链表中点,然后再判断回文
/**
* 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 the List is empty
if( head == NULL ){
return true;
}
// if the List has only 1 node
if( head->next == NULL ){
return true;
}
int n = 0;
ListNode * p1 = head;
ListNode * p2 = head;
// calculate how many digits should be checked
while(1)
{
p1 = p1->next;
if( p2->next == NULL ){
break;
}
else if ( p2->next->next == NULL ){
n++;
break;
}
else{
p2 = p2->next->next;
n++;
}
}
// check digits
for(int i=n-1; i>=0; i--){
ListNode * p = head;
for(int j=0; j<i; j++){
p = p->next;
}
if( p->val != p1->val ){
return false;
}
else if( p1->next != NULL ){
p1 = p1->next;
}
}
return true;
}
};
利用stack储存“慢”指针所读取的值,这样判断是否回文时可以就直接查询了
/**
* 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 the List is empty
if( head == NULL ){
return true;
}
// if the List has only 1 node
if( head->next == NULL ){
return true;
}
// if the List has 2 nodes
if( head->next->next == NULL ){
if( head->val != head->next->val ){
return false;
}
else return true;
}
stack<int> s;
int n = 0;
ListNode * p1 = head;
ListNode * p2 = head;
// calculate how many digits should be checked
while(1)
{
s.push(p1->val);
p1 = p1->next;
if( p2->next == NULL ){
s.pop();
break;
}
else if ( p2->next->next == NULL ){
n++;
break;
}
else{
p2 = p2->next->next;
n++;
}
}
// check digits
for(int i=0; i<n; i++){
if( s.top() != p1->val ){
return false;
}
s.pop();
p1 = p1->next;
}
return true;
}
};