回溯法 C代码
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
void dfs(struct ListNode *n, struct ListNode **ret, int i, int *count) {
if (n == NULL)
return;
(*count)++;
dfs(n->next, ret, i+1, count);
if(i == (((*count)/2) + 1)) { //注意点1:从1开始算,中间节点与下标的对应关系
*ret = n;
return;
}
}
struct ListNode* middleNode(struct ListNode* head){
struct ListNode *ret = NULL;
int count = 0;
dfs(head, &ret, 1, &count);
return ret;
}