思路:
遍历链表,用两个链表进行记录,遍历完成之后直接操作两个链表.
代码:
/**
* Definition of ListNode
* class ListNode {
* public:
* int val;
* ListNode *next;
* ListNode(int val) {
* this->val = val;
* this->next = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param head: The first node of linked list.
* @param x: an integer
* @return: a ListNode
*/
ListNode *partition(ListNode *head, int x) {
// write your code here
ListNode *small_head = nullptr, *small_tail = nullptr;
ListNode *big_head = nullptr, *big_tail = nullptr;
ListNode *tmp;
while(head){
tmp = head;
head = head->next;
tmp->next = nullptr;
if(tmp->val < x)
insertNode(small_head, small_tail, tmp);
else
insertNode(big_head, big_tail, tmp);
}// while
if(!small_head)
return big_head;
else if(!big_head)
return small_head;
small_tail->next = big_head;
return small_head;
}
void insertNode(ListNode *&head, ListNode *&tail, ListNode *node){
if(!head){
head = node;
tail = node;
return;
}
tail->next = node;
tail = tail->next;
}// insertNode
};