题解 | #链表分割#
链表分割
http://www.nowcoder.com/practice/0e27e0b064de4eacac178676ef9c9d70
class Partition {
public:
ListNode* partition(ListNode* pHead, int x) {
// write code here
ListNode* bigTail = NULL;
ListNode* bigHead = NULL; //大
ListNode* littleTail = NULL; //小
ListNode* littleHead = NULL;
littleTail = littleHead = (ListNode*)malloc(sizeof(ListNode));
littleTail->next = NULL;
bigTail = bigHead = (ListNode*)malloc(sizeof(ListNode));
bigTail->next = NULL;
ListNode* cur = pHead;
while(cur)
{
if(cur->val < x)
{
littleTail->next = cur;
littleTail = littleTail->next;
}
else
{
bigTail->next = cur;
bigTail = bigTail->next;
}
cur = cur->next;
}
littleTail->next = bigHead->next;
bigTail->next = NULL;//
pHead = littleHead->next;
free(bigHead);
free(littleHead);
return pHead;
}
};