Some common exercises

1. Reverse a single chain
Analysis: cur define a node, traverse the single list, when cur.next is empty, indicating that it has reached the end of the cur node, at this time, the rotation of the head node on the cur That happened cur its own rotation.
Specific achieve the following:

 public Node reverseList() {
        Node cur = this.head;
        Node prev = null;
        Node reverseHead = null;
        while(cur != null) {
            Node curNext = cur.next;
            if(curNext == null) {    //自身旋转
                reverseHead = cur;
            }
            cur.next = prev;
            prev = cur;
            
            cur = curNext; 
        }
        return reverseHead;
    }

2. Given a list, the list is determined whether a ring.
Analysis: Define two references, fast, slow fast each take two steps, slow each step, only one step between them. To see whether the two are equal, if it indicates that there is equal ring.
Note: Do not let time go fast 3-step, 4-step or five-step and the like, so fast is to go dancing, it is possible to meet, but time is very slow, there may never meet.
Implementation:


    //构造一个环
    public void createCycle() {
        Node cur = this.head;
        while(cur.next != null) {
            cur = cur.next;
        }
        cur.next = this.head.next.next.next;
    }

    public boolean hasCycle() {
        Node fast = this.head;
        Node slow = this.head;
        while(fast != null && fast.next!=null) {
            fast = fast.next.next;
            slow = slow.next;
            if(fast == slow) {
                return true;
            }
        }
        return false;
    }

3. Given a list, the list starts to return into the first ring node, if the chain acyclic, null is exchange
Analysis:
Here Insert Picture Description
As shown in FIG: fast and slow re-entry point was met

 public Node detectCycle() {
        Node fast = this.head;
        Node slow = this.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;
        }
        slow = this.head;
        while(fast != slow) {
            fast = fast.next;
            slow = slow.next;
        }
        return slow;
    }

Guess you like

Origin blog.csdn.net/weixin_42373873/article/details/89539657