#include<iostream>
#include<vector>
#include<stack>
using namespace std;
class ListNode {
public:
int val;
ListNode* next;
ListNode(int value) : val(value), next(nullptr) {
// 值 下一位
}
};
ListNode* BulidLinkedNode(vector<int> vec) {
if (vec.empty()) {
return nullptr;
}
ListNode* head = new ListNode(vec[0]);//开辟空间
ListNode* cur = head;
for (int i = 1; i < vec.size(); i++) {
cur->next = new ListNode(vec[i]);
cur = cur->next;
}
return head;
}
void print(ListNode* head, vector<int> vec) {
ListNode* pre = head;
for (int i = 0; i <= vec.size(); i++) {
cout << pre->val << endl;
pre = pre->next;
}
}
ListNode* Judgement(ListNode* head) {
ListNode* fast = head;
ListNode* slow = head;
while (fast->next != nullptr && fast->next->next != nullptr) {
fast = fast->next->next;
slow = slow->next;
}//双指针快指针的边界
cout << slow->val << endl;
return slow;
}
int Judge(ListNode* mid, ListNode* head) {
ListNode* cur = mid;
stack<int> stc;
while (cur != nullptr) {
stc.push(cur->val);
cur = cur->next;
}
ListNode* pre = head;
while (!stc.empty()) {
int num1 = stc.top();
int num2 = pre->val;
if (num1 != num2) {
cout << "false" << endl;
return 0;
}
stc.pop();
pre = pre->next;
}
cout << "true" << endl;
return 0;
}
int main() {
int n;
cin >> n;
vector<int> vec;
for (int i = 0; i < n; i++) {
int num;
cin >> num;
vec.push_back(num);
}
ListNode* list = BulidLinkedNode(vec);
ListNode* mid = Judgement(list);
Judge(mid, list);
print(list, vec);
return 0;
}
利用快慢指针判断,是否为回文