1. 程式人生 > >單鏈表判斷是否有環和環起始節點

單鏈表判斷是否有環和環起始節點

面試的滴滴研究院暑期實習生,崗位機器學習,二面除了電話面還要視訊面試寫程式碼,兩個問題:

  • 單鏈表判斷是否有環以及找出環開始的節點
  • 建立二叉排序樹並進行中序遍歷

因為第二個之前有寫過,所以沒什麼問題的過了;第一個其實也不難,但是有點緊張,最後面試官告訴我判斷是否有環的函式寫錯了,哎。。。特此重新寫下,mark之

package acmcoder;

class Node_t{
    int value;
    Node_t next;
    public Node_t(int value, Node_t next) {
        this.value
= value; this.next = next; } public Node_t() { value = -999; next = null; } @Override public String toString() { return "Node_t: value=" + value; } } public class Test_didi { private boolean hasLoop(Node_t head){ //使用快慢指標 Node_t p = head.next; Node_t q = head.next; boolean res = false
; while(q != null && q.next != null){ p = p.next; q = q.next.next; if(p == q){ res = true; break; } } return res; } private Node_t crashNode(Node_t head){ //假定一定有環 //使用快慢指標
Node_t p = head.next; Node_t q = head.next; while(q.next != null){ p = p.next; q = q.next.next; if(p == q){ break; } } return p; } private Node_t findCircleStartNode(Node_t head){ boolean hasCircle = hasLoop(head); if(!hasCircle){ return new Node_t(); }else{ //碰撞點到連線點的距離等於頭指標到連線點的距離 Node_t crash = crashNode(head); Node_t start = head.next; while(start != crash){ start = start.next; crash = crash.next; } return crash; } } private int circleLen(Node_t head){ //找到碰撞點之後從碰撞點出發然後再次碰撞 Node_t crash = crashNode(head); Node_t p = crash; Node_t q = crash; int len = 0; while(q.next != null){ p = p.next; q = q.next.next; len++; if(p == q){ break; } } return len; } public static void main(String[] args) { //建立單鏈表 Node_t node1 = new Node_t(1, null); Node_t node2 = new Node_t(2, null); Node_t node3 = new Node_t(3, null); Node_t node4 = new Node_t(4, null); Node_t node5 = new Node_t(5, null); Node_t node6 = new Node_t(6, null); node1.next = node2; node2.next = node3; node3.next = node4; node4.next = node5; node5.next = node6; node6.next = node4; //判斷是否有環 Test_didi test = new Test_didi(); boolean hs = test.hasLoop(node1); System.out.println("Has circle: " + hs); //找出環的起點 Node_t circleStart = test.findCircleStartNode(node1); System.out.println("Circle starts: " + circleStart.toString()); //計算環的長度 int len = test.circleLen(node1); System.out.println("Circle length: " + len); } }

雖然面的不好, 好在還是拿到了offer, 僥倖