未验证 提交 04b9ef55 编写于 作者: B BruceCat 提交者: GitHub

【234.回文链表】【 C++】

【234.回文链表】【 C++】
......@@ -237,4 +237,35 @@ p.next = reverse(q);
<img src="../pictures/qrcode.jpg" width=200 >
</p>
======其他语言代码======
\ 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即可
}
```
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册