Swimmer

[LeetCode] 876. Middle of the Linked List, C 본문

코딩 문제

[LeetCode] 876. Middle of the Linked List, C

Zach Choi 2022. 12. 28. 15:55

Idea

  • When we need to find median value, index -> we can use this algorithms
  • move two step forward agent, move onstep forward agent per scenario.
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* middleNode(struct ListNode* head){

    struct ListNode* first = head;
    struct ListNode* second = head;

    while(first && first->next)
    {
        second = second->next;
        first = first->next->next;
    }

    return second;
}

 

Comments