目录
1.剑指Offer
面试题22:链表中倒数第k个节点
题目描述:输入一个链表,输出该链表中倒数第k个结点。
思路:两个指针
代码:
class Solution {
public:
ListNode* FindKthToTail(ListNode* pListHead, unsigned int k) {
if(pListHead==nullptr||k==0){
return nullptr;
}
ListNode* pFront=pListHead;
int i=0;
for(;i<k-1;i++){
if(pFront->next==nullptr){
return nullptr;
}
pFront=pFront->next;
}
ListNode* pbehind=pListHead;
while(pFront->next!=nullptr){
pFront=pFront->next;
pbehind=pbehind->next;
}
return pbehind;
}
};
面试题23:链表中环的入口节点
题目描述:给一个链表,若其中包含环,请找出该链表的环的入口结点,否则,输出null。
思路:
1、设置快慢指针,假如有环,他们最后一定相遇。
2、两个指针分别从链表头和相遇点继续出发,每次走一步,最后一定相遇与环入口。
代码:
class Solution {
public:
ListNode* EntryNodeOfLoop(ListNode* pHead)
{
if(pHead==nullptr||(pHead!=nullptr&&pHead->next==nullptr)){
return nullptr;
}
ListNode* pFast=pHead;
ListNode* pSlow=pHead;
while(pFast!=nullptr&&pFast->next!=nullptr){
pFast=pFast->next->next;
pSlow=pSlow->next;
if(pFast==pSlow){
break;
}
}
if(pFast==nullptr||pFast->next==nullptr){
return nullptr;
}
pFast=pHead;
while(pFast!=pSlow){
pFast=pFast->next;
pSlow=pSlow->next;
}
return pFast;
}
};
2.Leetcode
例1:链表的中间节点
题目描述:
给定一个带有头结点 head
的非空单链表,返回链表的中间结点。
如果有两个中间结点,则返回第二个中间结点。
提示:
- 给定链表的结点数介于
1
和100
之间。
思路:快慢指针
代码:
class Solution {
public:
ListNode* middleNode(ListNode* head) {
if(head==nullptr){
return nullptr;
}
ListNode* pFast=head;
ListNode* pSlow=head;
while(pFast!=nullptr&&pFast->next!=nullptr){
pFast=pFast->next->next;
pSlow=pSlow->next;
}
return pSlow;
}
};