This is an extension of the question offer15.
The findmid method is used to obtain the intermediate node of the linked list (when the length of the list is unknown). The general idea is as follows:
1. First, define the slow and fast local variables in the method.
2. Slow repeats next once each time, and fast repeats next twice each time, when fast. when next = NULL, fast has reached the end of the linked list, and slow is just half of the linked list.
When this parameter is added, the first number of even numbers is returned. If this parameter is not added, the second number is returned.
if(fast==null){ break; }
Package stackmin. offer15_findkthtotail; public class midlink {public static void main (string [] ARGs) {listnode head = new listnode (1); listnode L2 = new listnode (2 ); listnode l3 = new listnode (3); listnode L4 = new listnode (4); listnode L5 = new listnode (5); listnode L6 = new listnode (6); head. next = L2; l2.next = l3; l3.next = L4; l4.next = L5; l5.next = L6; findmid (head);} Private Static void F Indmid (listnode head) {listnode slow = head; listnode fast = head; // while (fast! = NULL) {// If (fast. Next! = NULL) {// fast = fast. Next. Next; //} else {// break; //} // slow = slow. Next ;//}
Both the preceding and preceding statements can be used. While (fast! = NULL & fast. Next! = NULL) {fast = fast. next. next; // Add a comment to return 3, without adding 4 // If (fast = NULL) {// break; //} slow = slow. next;} system. out. println (slow. val );}}
Reference: [interview] returns the intermediate element of the linked list
Returns the intermediate element of the linked list.