C++ 中的链表循环 II
考虑我们有一个链表,而我们必须检查是否存在循环。为了在给定的链表中表示循环,我们将使用一个名为 pos 的整数指针。此 pos 表示链表中尾部连接到的位置。因此,如果 pos 为 -1,则链表中不存在循环。例如,链表为 [5, 3, 2, 0, -4, 7],pos = 1。因此,存在一个循环,并且尾部连接到第二个节点。约束是,我们无法修改列表。
为解决这个问题,我们将按照以下步骤操作:
- slow := head 和 fast := head
- 当 slow、fast 和 fast 的下一个可用时,然后
- slow := slow 的下一个
- fast := (fast 的下一个) 的下一个
- 如果 slow = fast,则中断
- 如果 fast 不为空或第一个的下一个不为空,则返回 null
- 如果 slow = fast,则
- slow := head
- 当 slow 与 fast 不同时
- slow := slow 的下一个和 fast := fast 的下一个
- 返回 slow
让我们看看以下实现以获得更好的理解:
示例
#include <bits/stdc++.h>
using namespace std;
class ListNode{
public:
int val;
ListNode *next;
ListNode(int data){
val = data;
next = NULL;
}
};
ListNode *make_list(vector<int> v){
ListNode *head = new ListNode(v[0]);
for(int i = 1; i<v.size(); i++){
ListNode *ptr = head;
while(ptr->next != NULL){
ptr = ptr->next;
}
ptr->next = new ListNode(v[i]);
}
return head;
}
ListNode *get_node(ListNode *head, int pos){
ListNode *ptr = head;
if(pos != -1){
int p = 0;
while(p < pos){
ptr = ptr->next;
p++;
}
return ptr;
}
return NULL;
}
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
ListNode* slow = head;
ListNode* fast = head;
while(slow && fast && fast->next){
slow = slow->next;
fast = fast->next->next;
if(slow == fast)break;
}
if(!fast || !fast->next)return NULL;
if(slow == fast){
slow = head;
while(slow!=fast){
slow = slow->next;
fast = fast->next;
}
}
return slow;
}
};
main(){
Solution ob;
vector<int> v = {5,3,2,0,-4,7};
ListNode *head = make_list(v);
int pos = 1;
ListNode *lastNode = get_node(head, v.size() - 1);
lastNode->next = get_node(head, pos);
cout << "Tail is connected to the node with value:" <<ob.detectCycle(head)->val;
}输入
[5,3,2,0,-4,7] 1
输出
Tail is connected to the node with value:3
Advertisement 广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP