回文数字判断

#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;
}

利用快慢指针判断,是否为回文

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值