日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

【剑指offer】面试题23:链表中环的入口节点

發(fā)布時(shí)間:2024/7/19 编程问答 30 豆豆
生活随笔 收集整理的這篇文章主要介紹了 【剑指offer】面试题23:链表中环的入口节点 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

一個(gè)鏈表中包含環(huán),請找出該鏈表的環(huán)的入口結(jié)點(diǎn)

代碼:

package offer;
class Node3
{
?? ?int val;
?? ?Node3 next = null;
?? ?Node3(int val)
?? ?{
?? ??? ?this.val = val;
?? ?}
}
public class ti23 {
?? ?public static Node3 FindInterNode(Node3 head)
?? ?{
?? ??? ?if(head==null||head.next==null)
?? ??? ?{
?? ??? ??? ?return null;
?? ??? ?}
?? ??? ?Node3 fast = head;//快指針每次走兩步
?? ? ? ?Node3 slow = head;//每次走一步
?? ? ? ? ? while(fast!=null && fast.next !=null)//因?yàn)閒ast每次要走兩步,所有需要判斷fast的下一個(gè)是否為空
?? ? ? ? ? {
?? ? ? ??? ? ? slow = slow.next;
?? ? ? ??? ? ? fast = fast.next.next;
?? ? ? ??? ? ? //判斷是否相遇 相遇后讓快指針從頭開始走,每次都是走一步,第二次相遇的節(jié)點(diǎn)就是環(huán)的入口
?? ? ? ??? ? ? if(fast.val == slow.val)
?? ? ? ??? ? ? {
?? ? ? ??? ??? ? ?fast = head;
?? ? ? ??? ??? ? ?while(fast.val != slow.val)
?? ? ? ??? ??? ? ?{
?? ? ? ??? ??? ??? ? ?fast = fast.next;
?? ? ? ??? ??? ??? ? ?slow = slow.next;
?? ? ? ??? ??? ? ?}
?? ? ? ??? ? ? }
?? ? ? ??? ? ? if(fast.val == slow.val)
?? ? ? ??? ? ? {
?? ? ? ??? ??? ? ? return slow;
?? ? ? ??? ? ? }
?? ? ? ? ? }
?? ? ? ? ? return null;//要是沒有相遇,此鏈表沒有環(huán)返回空
?? ?}
?? ?public static void main(String[] args)
?? ?{
?? ??? ?Node3 node1 = new Node3(1);
?? ??? ?Node3 node2 = new Node3(2);
?? ??? ?Node3 node3 = new Node3(3);
?? ??? ?Node3 node4 = new Node3(4);
?? ??? ?Node3 node5 = new Node3(5);
?? ??? ?Node3 node6 = new Node3(6);
?? ??? ?node1.next = node2;
?? ??? ?node2.next = node3;
?? ??? ?node3.next = node4;
?? ??? ?node4.next = node5;
?? ??? ?node5.next = node6;
?? ??? ?Node3 head = node1;
?? ??? ?node6.next = node3;
?? ??? ?System.out.println(FindInterNode(head).val);
?? ?}
}
?

總結(jié)

以上是生活随笔為你收集整理的【剑指offer】面试题23:链表中环的入口节点的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。