0323-2020-LEETCODE-876- intermediate node of the list - (list or speed memory pointer)

Just looking as the penultimate K elements, using the pointer speed can be achieved once traversed, the penultimate of K is: Slow pointer until the pointer to go fast walk after K steps until the pointer quickly come to the end of the list, too slow pointer K went to the penultimate one.
This is the same, equivalent binary, then a full pointer on a walk, a two-step two-step quick pointers, pointer just know soon come to the end of the list or go to the next null pointer at the end of the list, the termination condition is very important .
More general idea is they want to create a list of container, directly followed by addition of the last to return half the size of the list.

public ListNode middleNode(ListNode head) {
        if (head == null){
            return null;
        }
        int count = 0;
        ArrayList<ListNode> list = new ArrayList<>();
        while (head != null){
            list.add(head);
            head = head.next;
            count++;
        }
        //int index = count % 2 == 0 ? count / 2 + 1 : count / 2;
        return list.get(count / 2);
    }
    public ListNode middleNode1(ListNode head) {
        if (head == null){
            return null;
        }
        ListNode slow = head;
        ListNode fast = head;
        while (fast != null && fast.next != null){
            slow = slow.next;
            fast = fast.next.next;
        }
        return slow;
    }

    public void print(ListNode head){
        while (head != null){
            System.out.print(head.val + " ");
            head = head.next;
        }
    }
Published 98 original articles · won praise 0 · Views 2186

Guess you like

Origin blog.csdn.net/weixin_43221993/article/details/105042246
Recommended