Returns the intermediate element of the linked list.

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.