题解 | #牛群分隔# 链表应用题
牛群分隔
https://www.nowcoder.com/practice/16d9dc3de2104fcaa52679ea796e638e
知识点
链表
思路解析
思路很简单, 建立两个虚拟头结点, 依次遍历原链表, 小于x的接在一边, 大于等于x的接在另外一边
最后把两个链表连起来即可
时间复杂度
由于只遍历一次链表
AC code (C++)
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) : val(x), next(nullptr) {}
* };
*/
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param head ListNode类
* @param x int整型
* @return ListNode类
*/
ListNode* cow_partition(ListNode* head, int x) {
// write code here
auto dummy1 = new ListNode(-1);
auto dummy2 = new ListNode(-1);
auto less = dummy1, more = dummy2;
auto p = head;
while (p) {
if (p->val < x) {
less->next = p;
less = less->next;
}
else {
more->next = p;
more = more->next;
}
p = p->next;
}
less->next = dummy2->next;
more->next = nullptr;
return dummy1->next;
}
};
查看2道真题和解析