题意
给定一个链表和数x,要求把小于x的数挪到链表前面,大于或等于x的数挪到x后面,并且保持链表的相对顺序不变。
思路
新开两个链表first和second,然后遍历原来的链表,小于x的挂到first上,大于等于x的挂到second上,然后把两个链表串起来就好。
代码
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* partition(ListNode* head, int x) {
if (!head) return head;
ListNode *cur = head;
ListNode *first = NULL, *second = NULL, *firsthead = NULL, *secondhead = NULL;
while (cur) {
//cout << cur->val << endl;
if (cur->val < x) {
if (!first) {first = cur; firsthead = cur;}
else {first->next = cur; first = first->next;}
} else {
if (!second) {second = cur; secondhead = cur;}
else {second->next = cur; second = second->next;}
}
cur = cur->next;
}
if (!firsthead) return secondhead;
first->next = secondhead;
//this is necessary;
if (second) second->next = NULL;
return firsthead;
}
};