题解 | #牛群的编号重排#
牛群的编号重排
https://www.nowcoder.com/practice/2e4baac1b994494e83a7c0b17b97ac2d
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) : val(x), next(nullptr) {}
* };
*/
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param head ListNode类
* @return ListNode类
*/
ListNode* reorderCows(ListNode* head) {
// write code here
auto head1 = new ListNode(-1);
auto head2 = new ListNode(-1);
auto h1end = head1;
auto h2end = head2;
ListNode* pre = nullptr;
int count = 0;
while(head!=nullptr){
count ++;
if(count % 2 == 0){
h2end->next = head;
h2end = h2end->next;
}
else{
h1end->next = head;
h1end = h1end->next;
}
auto n_node = head->next;
head -> next = nullptr;
head = n_node;
}
h1end->next = head2->next;
return head1->next;
}
};


查看4道真题和解析