题解 | #牛的品种排序IV# 链表模拟
牛的品种排序IV
https://www.nowcoder.com/practice/bd828af269cd493c86cc915389b02b9f
知识点
链表
思路
遍历整个链表,建立两个虚拟头结点,一个作为0的起点,一个作为1的起点。之后将两段拼接即可。
时间复杂度为
AC code (C++)
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) : val(x), next(nullptr) {}
* };
*/
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param head ListNode类
* @return ListNode类
*/
ListNode* sortCowsIV(ListNode* head) {
auto d0 = new ListNode(-1);
auto d1 = new ListNode(-1);
auto p = d0, q = d1;
while (head) {
if (head->val) {
q->next = head;
q = q->next;
}
else {
p->next = head;
p = p->next;
}
head = head->next;
}
p->next = d1->next;
q->next = nullptr;
return d0->next;
}
};
