【leetcode 141】环形链表
https://leetcode-cn.com/problems/linked-list-cycle/submissions/
解题思路:定义两个指针,一个快指针,一个慢指针,如果链表有环,快指针一定会追上慢指针。
总结:我们只需要遍历整个链表,在遍历的过程中记录我们经历过的节点。
如果遇到next节点为null,说明没有还。
如果遇到我们以前遍历过的节点,说明有环。
C++语言实现:
class Solution {
public:
bool hasCycle(ListNode *head) {
//特判:
if(head == nullptr) return false;
//定义两个指针,p慢指针,q是快指针
ListNode *p = head, *q = head->next;
while(p != q && q && q->next){
p = p->next;
q = q->next->next;
}
return q && q->next;
}
};
环形链表进阶:
【leetcode 142】环形链表||
https://leetcode-cn.com/problems/linked-list-cycle-ii/submissions/
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
// if(head == nullptr) return nullptr;//没有返回空地址
// ListNode *p = head,*q = head->next;
// while(p != q && q && q->next){
// p = p->next;
// q = q->next->next;
// }
// if(q == nullptr || q->next == nullptr) return nullptr;
// p = head->next,q = head->next->next;
// while(p != q){
// p = p->next;
// q = q->next->next;
// }
// p = head;
// while( p!= q){
// p = p->next;
// q = q->next;
// }
// return q;
//写法二:
//没有返回空地址
if(head == nullptr || head->next == nullptr) return nullptr; ListNode *p = head,*q = head;
do{
p = p->next;
q = q->next->next;
}while(p != q && q && q->next);
if(q == nullptr || q->next == nullptr) return nullptr;
p = head;
while(p != q) p = p->next,q = q->next;
return q;
}
};
【leetcode 201】快乐数
https://leetcode-cn.com/problems/happy-number/
题目可以转化为,判断一个链表是否有环。
如果遍历某个节点为1,说明没有环,就是快乐数。
如果遍历到重复的节点值,说明有环,就不是快乐数。
class Solution {
public:
int getNext(int x){
int z = 0;
while(x){
z += (x % 10) * (x % 10);
x /= 10;
}
return z;
}
bool isHappy(int n) {
//定义两个指针,p是慢指针,q是慢指针
int p = n,q = n;
do{
p = getNext(p);
q = getNext(getNext(q));
}while(p != q && q != 1);
return q == 1;
}
};
补充:
数据映射到最大的数字是多大?
数据类型是整型的
1+9个9的数字:
1999999999 -> 81*9+1 = 730个节点(估算链表的思维方式,不会超过731个链表节点)
最后,算法是分析问题和解决问题的能力!!
up!!!