From 0a4bddfe2b3a540476920d50c17c6457e86344be Mon Sep 17 00:00:00 2001 From: forthespada <44971298+forthespada@users.noreply.github.com> Date: Wed, 11 Nov 2020 16:21:27 +0800 Subject: [PATCH] =?UTF-8?q?=E3=80=90234.=E6=BB=91=E5=8A=A8=E7=AA=97?= =?UTF-8?q?=E5=8F=A3=E6=9C=80=E5=A4=A7=E5=80=BC=E3=80=91=E3=80=90=E5=9B=9E?= =?UTF-8?q?=E6=96=87=E9=93=BE=E8=A1=A8=E3=80=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...36\346\226\207\351\223\276\350\241\250.md" | 33 ++++++++++++++++++- 1 file changed, 32 insertions(+), 1 deletion(-) diff --git "a/\351\253\230\351\242\221\351\235\242\350\257\225\347\263\273\345\210\227/\345\210\244\346\226\255\345\233\236\346\226\207\351\223\276\350\241\250.md" "b/\351\253\230\351\242\221\351\235\242\350\257\225\347\263\273\345\210\227/\345\210\244\346\226\255\345\233\236\346\226\207\351\223\276\350\241\250.md" index 3e24068..4d0225a 100644 --- "a/\351\253\230\351\242\221\351\235\242\350\257\225\347\263\273\345\210\227/\345\210\244\346\226\255\345\233\236\346\226\207\351\223\276\350\241\250.md" +++ "b/\351\253\230\351\242\221\351\235\242\350\257\225\347\263\273\345\210\227/\345\210\244\346\226\255\345\233\236\346\226\207\351\223\276\350\241\250.md" @@ -237,4 +237,35 @@ p.next = reverse(q);

-======其他语言代码====== \ No newline at end of file +======其他语言代码====== + +C++版本: +```cpp + bool isPalindrome(ListNode* head) { + if (head == nullptr || head->next == nullptr) //为空或者只有一个节点时,直接判断为true + return true; + ListNode* slow = head, * fast = head; + while (fast != nullptr) {//首先找到中间节点 + slow = slow->next; + fast = fast->next == nullptr? fast->next:fast->next->next; //因为链表长度可能是奇数或偶数,所以需要进行判断 + } + + ListNode* temp = nullptr,* pre = nullptr;//pre始终保持后续链表的头部,temp节点则作为中间零时替换的节点 + while (slow != nullptr) {//利用头插法,将当前节点与后续链表断链处理,反转后半部分的链表 + temp = slow->next; + slow->next = pre;//建立连接 + pre = slow;//pre始终作为后续链表的头部 + slow = temp; + } + + while (head !=nullptr && pre != nullptr) {//同步进行比较 + if (head->val != pre->val) {//值有不一样的,说明不是回文联表,直接返回false了 + return false; + } + head = head->next;//head向下走,直到走到空 + pre = pre->next;//pre节点也向下走,直到走到空 + } + return true;//到此说明当前链表是回文链表返回true即可 + } + +``` -- GitLab