给定一个列表,将其分成两个子列表——一个用于前半部分,一个用于后半部分。如果元素的数量是奇数,则额外的元素应该放在前面的列表中。所以FrontBackSplit()
在列表上{2, 3, 5, 7, 11}
应该产生两个列表{2, 3, 5}
和{7, 11}
。
代码是这样的。
void FrontBackSplit(Node *head, Node **front, Node **back) {
if (!head) return; // Handle empty list
Node *front_last_node;
Node *slow = head;
Node *fast = head;
while (fast) {
front_last_node = slow;
slow = slow->next;
fast = (fast->next) ? fast->next->next : NULL;
}
front_last_node->next = NULL; // ends the front sublist
*front = head;
*back = slow;
}
问题是我没有得到最好的运行时间,有时也没有得到预期的输出。