c++代码:判断链表是否为回文链表
#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 || !head->next) return true;
ListNode* slow = head;
ListNode* fast = head;
while (fast->next && fast->next->next) {
slow = slow->next;
fast = fast->next->next;
}
stack<int> s;
while (slow->next) {
slow = slow->next;
s.push(slow->val);
}
while (!s.empty()) {
if (head->val != s.top()) return false;
s.pop();
head = head->next;
}
return true;
}
int main() {
ListNode* head = new ListNode(1);
head->next = new ListNode(2);
head->next->next = new ListNode(2);
head->next->next->next = new ListNode(1);
cout << isPalindrome(head) << endl; // 输出1,即为true
return 0;
}
原文地址: https://www.cveoy.top/t/topic/bbEI 著作权归作者所有。请勿转载和采集!