题目:将链表分成前后2部分,一部分小于x,另一部分不小于x,且保留各元素的相对位置
分析:再建2个链表分别保存小的和大的,然后合并
答案:
/**
* 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) {
ListNode *smallList = new ListNode(0);
ListNode *largeList = new ListNode(0);
ListNode *cur = head;
ListNode *smallListTail = smallList;
ListNode *largeListTail = largeList;
while(cur){
if (cur->val < x){
smallListTail->next = cur;
smallListTail =cur;
}else{
largeListTail->next = cur;
largeListTail =cur;
}
ListNode *nextp = cur->next;
cur->next = NULL;
cur = nextp;
}
if (smallList->next == NULL)
return largeList->next;
else{
smallListTail->next = largeList->next;
return smallList->next;
}
}
};