【nowcoder】链表的回文结构
发布时间:2024年01月24日
牛客题目链接 链表的回文结构
#include <cstdlib>
class PalindromeList {
public:
bool chkPalindrome(ListNode* A) {
ListNode* slow = A, * fast = A;
while (fast && fast->next) {
slow = slow->next;
fast = fast->next->next;
}
ListNode* cur = NULL, * next = NULL;
while (slow) {
next = slow->next;
slow->next = cur;
cur = slow;
slow = next;
}
next = A;
while (cur) {
if (next->val != cur->val) {
return false;
}
next = next->next;
cur = cur->next;
}
return true;
}
bool chkPalindrome_(ListNode* A) {
ListNode* B = NULL;
ListNode* curA = A;
while (curA) {
ListNode* newNode = (ListNode*)malloc(sizeof(ListNode));
newNode->val = curA->val;
newNode->next = NULL;
if (B == NULL) {
B = newNode;
}
else {
newNode->next = B;
B = newNode;
}
curA = curA->next;
}
curA = A;
ListNode* curB = B;
while (curA) {
if (curA->val != curB->val) {
return false;
}
curA = curA->next;
ListNode* del = curB;
curB = curB->next;
free(del);
del = NULL;
}
return true;
}
};
文章来源:https://blog.csdn.net/m0_52602233/article/details/135661228
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若内容造成侵权/违法违规/事实不符,请联系我的编程经验分享网邮箱:chenni525@qq.com进行投诉反馈,一经查实,立即删除!