当前位置:网站首页>LeetCode Algorithm 剑指 Offer II 027. 回文链表
LeetCode Algorithm 剑指 Offer II 027. 回文链表
2022-06-24 19:38:00 【Alex_996】
Ideas
算法:双指针
数据结构:链表
思路:首先把链表的后半段翻转过来,然后用两个指针分别从头和从中间开始遍历判断是否相同,如果相同则是回文链表,否则不是回文链表,但不管是不是回文链表,翻转的链表还是要翻转回去。
1.用快慢指针,快指针quick一次走两步,慢指针slow一次走一步,当快指针到头时,慢指针正好到链表中间;(如果链表长度为奇数,快指针最终走到最后一个元素,如果链表长度为偶数,快指针最终走到倒数第二个元素)
2.从链表中间开始,将后面的节点逐个翻转,即当前节点原本指向下一个节点,改为指向前一个节点;
3.双指针分别从链表的头尾出发,遍历判断当前节点值是否相等,最终双指针相遇时截止;
4.从链表中间开始,再将后面的节点翻转回去。
Code
C++
class Solution {
public:
bool isPalindrome(ListNode* head) {
if (head == nullptr || head->next == nullptr) {
return true;
}
// 1.快慢指针找到链表中间位置
ListNode *quick = head, *slow = head;
while (quick->next != nullptr && quick->next->next != nullptr) {
slow = slow->next;
quick = quick->next->next;
}
// 2.从链表中间位置开始将后续节点翻转
ListNode *cur = slow->next;
slow->next = nullptr;
while (cur != nullptr) {
ListNode *nxt = cur->next;
cur->next = slow;
slow = cur;
cur = nxt;
}
// 3.双指针分别从头尾开始遍历
bool res = true;
quick = head;
ListNode *tail = slow;
while (quick != nullptr && slow != nullptr) {
if (quick->val != slow->val) {
res = false;
break;
}
quick = quick->next;
slow = slow->next;
}
// 4.将翻转的节点再翻转回去
cur = tail->next;
tail->next = nullptr;
while (cur != nullptr) {
ListNode *nxt = cur->next;
cur->next = tail;
tail = cur;
cur = nxt;
}
return res;
}
};
当然,如果你觉得双指针比较麻烦的话,也可以遍历链表保存到数组中再判断是否为回文。
class Solution {
public:
bool isPalindrome(ListNode* head) {
vector<int> values;
while (head) {
values.push_back(head->val);
head = head->next;
}
for (int i = 0, j = values.size() - 1; i < j; i++, j--) {
if (values[i] != values[j]) {
return false;
}
}
return true;
}
};
Python
class Solution:
def findFirstHalfEnd(self, node):
fast = slow = node
while fast.next is not None and fast.next.next is not None:
fast = fast.next.next
slow = slow.next
return slow
def reverseList(self, node):
previous, current = None, node
while current is not None:
nextNode = current.next
current.next = previous
previous = current
current = nextNode
return previous
def isPalindrome(self, head: ListNode) -> bool:
# 判断边界情况
if head is None:
return True
# 找到前半部分链表的为节点并反转后半部分链表
firstHalfEnd = self.findFirstHalfEnd(head)
secondHalfStart = self.reverseList(firstHalfEnd.next)
# 判断是否为回文
ans, firstPosition, secondPosition = True, head, secondHalfStart
while ans and secondPosition is not None:
if firstPosition.val != secondPosition.val:
return False
firstPosition = firstPosition.next
secondPosition = secondPosition.next
# 还原反转的链表
firstHalfEnd.next = self.reverseList(secondHalfStart)
return ans
边栏推荐
- CSRF and SSRF for web attacks
- Principles of Ethernet port mirroring, link aggregation and VLAN Technology
- img2pdf
- Future development of education industry of e-commerce Express
- Publicity of the second batch of shortlisted enterprises! Annual Top100 smart network supplier selection
- 【软件工程】期末重点
- 网上立案流程
- STP spanning tree protocol Foundation
- Interrupt, interrupted, isinterrupted differences
- Idea close global search box
猜你喜欢

Docker installs MySQL 8.0. Detailed steps

Cache control of HTTP

A girl has been making hardware for ten years. 。。

Row and column differences in matrix construction of DX HLSL and GL glsl

In the multi network card environment, the service IP registered by Nacos is incorrect, resulting in inaccessible services

nuScenes——数据集配置过程中遇到图像文件缺失或大小为0时的补救方法

Ideal L9, new trend of intelligent cockpit

Introduction, installation and use of postman tool

Cross border e-commerce, early entry and early benefit
How to solve the problem that the computer suddenly can't connect to WiFi
随机推荐
Problèmes de concurrence dans l'allocation de mémoire en tas
Fanuc robot_ Introduction to Karel programming (1)
OSPF basic content
干货丨产品的可行性分析要从哪几个方面入手?
HTTP的缓存控制
第二批入围企业公示!年度TOP100智能网联供应商评选
In the first year of L2, arbitrum nitro was upgraded to bring more compatible and efficient development experience
Uncover the secret of station B. is it true that programmers wear women's clothes and knock code more efficiently?
Nuscenes -- remedies for missing image files or 0-size images encountered during dataset configuration
短视频商城系统,scroll-view如何自适应页面剩余高度
[Software Engineering] key points at the end of the period
CDN principle
Principle of IP routing
Genesis公链与美国一众加密投资者齐聚Consensus 2022
Interrupt, interrupted, isinterrupted differences
Cache control of HTTP
Data communication foundation - Ethernet port mirroring and link aggregation
Row and column differences in matrix construction of DX HLSL and GL glsl
Introduction, installation and use of postman tool
NIO、BIO、AIO