c++代码:请编写算法判断链表是否为回文链表。以1 2和1 2 2 1和1 2 3 2 1为例验证代码成功
#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, *fast = head;
stack<int> s;
while (fast != NULL && fast->next != NULL) {
s.push(slow->val);
slow = slow->next;
fast = fast->next->next;
}
if (fast != 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; // 输出 0
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
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
return 0;
}
原文地址: https://www.cveoy.top/t/topic/bbMX 著作权归作者所有。请勿转载和采集!