c++代码:请编写算法判断链表是否为回文链表。以1 2和1 2 2 1和1 2 3 2 1为例验证代码成功。如果是返回 true ;否则返回 false。
#include<iostream>
#include<stack>
using namespace std;
struct ListNode{
int val;
ListNode *next;
ListNode(int x):val(x),next(NULL){}
};
bool isPalindrome(ListNode* head){
if(head==NULL || head->next==NULL) return true; //空链表或只有一个结点的链表是回文链表
ListNode* slow=head; //慢指针
ListNode* fast=head; //快指针
stack<int> s; //栈
s.push(head->val); //将头结点的值入栈
while(fast->next!=NULL && fast->next->next!=NULL){ //快指针遍历完链表时,慢指针正好在链表中间
slow=slow->next;
fast=fast->next->next;
s.push(slow->val); //将慢指针的值入栈
}
if(fast->next!=NULL) slow=slow->next; //链表结点数为奇数时,慢指针需要再向后移动一位
while(slow!=NULL){ //从中间向两端遍历链表,同时比较栈中的值
if(s.top()!=slow->val) return false;
s.pop();
slow=slow->next;
}
return true;
}
int main(){
ListNode* head1=new ListNode(1);
head1->next=new ListNode(2);
cout<<isPalindrome(head1)<<endl; //1 2,输出1
ListNode* head2=new ListNode(1);
head2->next=new ListNode(2);
head2->next->next=new ListNode(2);
head2->next->next->next=new ListNode(1);
cout<<isPalindrome(head2)<<endl; //1 2 2 1,输出1
ListNode* head3=new ListNode(1);
head3->next=new ListNode(2);
head3->next->next=new ListNode(3);
head3->next->next->next=new ListNode(2);
head3->next->next->next->next=new ListNode(1);
cout<<isPalindrome(head3)<<endl; //1 2 3 2 1,输出1
return 0;
}
原文地址: https://www.cveoy.top/t/topic/bbNz 著作权归作者所有。请勿转载和采集!