当前位置:网站首页>[876. intermediate node of linked list]

[876. intermediate node of linked list]

2022-06-22 21:05:00 Cat star people who love Durian


One 、 Title Description

Given a header node as head The non empty single chain table of , Returns the middle node of the linked list .
If there are two intermediate nodes , Then return to the second intermediate node .

Example 1:

Input :[1,2,3,4,5]
Output : Nodes in this list 3 ( Serialization form :[3,4,5])
The returned node value is 3 . ( The evaluation system expresses the serialization of this node as follows [3,4,5]).
Be careful , We returned one ListNode Object of type ans, such :
ans.val = 3, ans.next.val = 4, ans.next.next.val = 5, as well as ans.next.next.next = NULL.

Example 2:

Input :[1,2,3,4,5,6]
Output : Nodes in this list 4 ( Serialization form :[4,5,6])
Because the list has two intermediate nodes , Values, respectively 3 and 4, Let's go back to the second node .

Tips :

The number of nodes in a given list is between 1 and 100 Between .

source : Power button (LeetCode)
link :https://leetcode.cn/problems/middle-of-the-linked-list


Two 、 Provide easy to read code diagram

 Insert picture description here


3、 ... and 、 Title code

Ideas : Speed pointer

/** * Definition for singly-linked list. * struct ListNode { * int val; * struct ListNode *next; * }; */


struct ListNode* middleNode(struct ListNode* head){
    
    struct ListNode*slow=head;
    struct ListNode*first=head;
    while(first&&first->next)
    {
    
       if(first->next)
       {
    
         slow=slow->next;
         first=first->next->next;
       }
    }
    return slow;
}

The above is the whole content of this article , If there are mistakes in the article or something you don't understand , Communicate more with meow bloggers . Learn from each other and make progress . If this article helps you , Can give meow bloggers a concern , Your support is my biggest motivation .

原网站

版权声明
本文为[Cat star people who love Durian]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/173/202206221941074116.html