/** * Definition for singly-linked list. * struct ListNode { * int val; * struct ListNode *next; * }; */ struct ListNode* middleNode(struct ListNode* head) { structListNode *current = head; structListNode *middle=NULL; int counter=0; int middleNodeIndex; bool isEven;
// (1) Get the length of list (2) Get the index of the middle while (current != NULL){ counter++; if(counter%2 == 0){ isEven = true; middleNodeIndex = counter/2; } else{ isEven = false; middleNodeIndex = (int)(floor(counter/2)); } current = current->next; } // Traverse to the middle node, and return middle node current = head; for (int i=0; i<counter; i++){ if ( i == middleNodeIndex){ middle = current; break; } current = current->next; } return middle;
說明
初始化變數:
current 用於遍歷鏈結串列,middle 用於儲存中間節點,counter 用於計算節點總數,middleNodeIndex 用於儲存中間節點的索引,isEven 用於判斷節點數是否為偶數
voidFreeList(Node* first){ Node *tmp, *current; current = first; while(current != NULL){ tmp = current; current = current->next; free(tmp); }
}
Node * middleNode(Node *first){ Node *current = first; Node *middle= NULL; int counter=0; int middleNodeIndex; bool isEven;
// (1) Get the length of list (2) Get the index of the middle while (current != NULL){ counter++; if(counter%2 == 0){ isEven = true; middleNodeIndex = counter/2; } else{ isEven = false; middleNodeIndex = (int)(floor(counter/2)); } current = current->next; }
current = first; for (int i=0; i<counter; i++){ if ( i == middleNodeIndex){ middle = current; break; } current = current->next; } return middle; }
執行結果
大概執行時間是 3ms,並不太算是效能良好的寫法 空間也用的挺多,5.66MB
修正程式碼
1 2 3 4 5 6 7 8 9 10 11 12 13 14
// (1) Get the length of list (2) Get the index of the middle while (current != NULL){ counter++; if(counter%2 == 0){ isEven = true; middleNodeIndex = counter/2; } else{ isEven = false; middleNodeIndex = (int)(floor(counter/2)); } current = current->next; }
// (1) Get the length of list (2) Get the index of the middle while (current != NULL){ counter++; middleNodeIndex = (int)(floor(counter/2)); current = current->next; }
執行結果也會大幅提升
其他做法
在解答區看到一個寫得很讚的作法,他的想法是:
想像你跟你朋友正要爬樓梯
你們都站在樓梯底部
你每次爬一階,而你朋友每次爬兩階 (你的平均上樓速度會是你朋友的一半)
當他爬到頂端,你就停下 (恰好會待在樓梯的一半位置)
步驟
Initialization: Start with two pointers, fast and slow, both pointing to the head of the list.
Traversal: Move the fast pointer two steps at a time and the slow pointer one step at a time. This ensures that when the fast pointer reaches the end of the list, the slow pointer will be at the middle node.
Find the Middle Node: After traversal, the slow pointer will be at the middle node of the list.
Edge Case Handling: Check if the list is empty or contains only one node. In such cases, the middle node is the head itself.
Return: Return the node pointed to by the slow pointer as the middle node.