网站公司简介模板免费下载,wordpress批量删除,网站建设的一般流程是,上海比较好的seo公司环形链表Ⅱ 给定一个链表的头节点 head #xff0c;返回链表开始入环的第一个节点。 如果链表无环#xff0c;则返回 null。
如果链表中有某个节点#xff0c;可以通过连续跟踪 next 指针再次到达#xff0c;则链表中存在环。 为了表示给定链表中的环#xff0c;评测系统…环形链表Ⅱ 给定一个链表的头节点 head 返回链表开始入环的第一个节点。 如果链表无环则返回 null。
如果链表中有某个节点可以通过连续跟踪 next 指针再次到达则链表中存在环。 为了表示给定链表中的环评测系统内部使用整数 pos 来表示链表尾连接到链表中的位置索引从 0 开始。如果 pos 是 -1则在该链表中没有环。注意pos 不作为参数进行传递仅仅是为了标识链表的实际情况。
不允许修改 链表。
示例 1 输入head [3,2,0,-4], pos 1
输出返回索引为 1 的链表节点
解释链表中有一个环其尾部连接到第二个节点。示例 2 输入head [1,2], pos 0
输出返回索引为 0 的链表节点
解释链表中有一个环其尾部连接到第一个节点。示例 3
外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传
输入head [1], pos -1
输出返回 null
解释链表中没有环。思路 Java版本
public class Solution {public ListNode detectCycle(ListNode head) {if(head null) return null;ListNode fast head;ListNode slow head;while(fast ! null fast.next ! null){fast fast.next.next;slow slow.next;if(fast slow) {break;}} if(fast null || fast.next null){return null;}fast head;while(fast ! slow){fast fast.next;slow slow.next;}return fast;}
}public class Solution {public ListNode detectCycle(ListNode head) {ListNode fast head;ListNode slow head;while(fast ! null fast.next ! null){slow slow.next;fast fast.next.next;if(slow fast){ListNode index1 fast;ListNode index2 head;while(index1 ! index2){index1 index1.next;index2 index2.next;}return index2;}}return null;}
}C版本
class Solution {
public:ListNode *detectCycle(ListNode *head) {ListNode* fast head;ListNode* slow head;while(fast ! NULL fast-next ! NULL){slow slow-next;fast fast-next-next;//有环if(slow fast){ListNode* index1 fast;ListNode* index2 head;while(index1 ! index2){index1 index1-next;index2 index2-next;} return index1;}}return NULL;}
};