作者sustainer123 (caster )
看板Marginalman
標題[閒聊] LeetCode 876
時間Fri Jan 6 13:24:16 2023
876. Middle of the Linked List
給你一個linked list,請找出它的middle node,
如長度為偶數,中間有二middle node,則取第二個。
Example 1:
Input: head = [1,2,3,4,5]
Output: [3,4,5]
Explanation: The middle node of the list is node 3.
Input: head = [1,2,3,4,5,6]
Output: [4,5,6]
Explanation: Since the list has two middle nodes with values 3 and 4, we
return the second one.
思路:
linked list無法直接得知長度,所以先設另一linked list為i,使i=head,
將i跑完一遍,便能得知長度。
之後將長度/2,為了使小數點進位,所以加上round()函式。
最後用迴圈跑出middle node,回傳head。
C Code
-------------------------
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
#include <math.h>
struct ListNode* middleNode(struct ListNode* head){
struct ListNode* i = head;
int length = 0;
while( i != NULL){
i = i->next;
length++;
}
int middle = round(length/2);
int cur=0;
while(cur < middle){
head = head->next;
cur++;
}
return head;
}
--------------------------
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 114.43.115.198 (臺灣)
※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1672982659.A.202.html
推 SecondRun: 大師 01/06 13:26
推 Jaka: 大師 01/06 13:29
→ sustainer123: 你們才是大師 我等等要刷第一題medium 覺得恐慌 01/06 13:34