题解 | #划分链表#
划分链表
http://www.nowcoder.com/practice/1dc1036be38f45f19000e48abe00b12f
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
class Solution {
public:
/**
*
* @param head ListNode类
* @param x int整型
* @return ListNode类
*/
ListNode* partition(ListNode* head, int x) {
// write code here
if(!head || !head->next)
return head;
ListNode* start = new ListNode(-1);
start->next = head;
auto p = head;
while(p->next != nullptr) p = p->next;
auto q = start;
auto end = p;
while(q->next != end) {
if(q->next->val >= x) {
p->next = q->next;
q->next = q->next->next;
p->next->next = nullptr;
p = p->next;
}else {
q = q->next;
}
}
if(end->val >= x) { // 特判
p->next = end;
q->next = end->next;
end->next = nullptr;
}
return start->next;
}
};