题解 | #链表分割#
链表分割
https://www.nowcoder.com/practice/0e27e0b064de4eacac178676ef9c9d70
/* struct ListNode { int val; struct ListNode *next; ListNode(int x) : val(x), next(NULL) {} };*/ class Partition { public: ListNode* partition(ListNode* phead, int x) { // write code here struct ListNode* cur, *lesshead, *lesstail, *greaterhead, *greatertail; cur = phead; lesshead = (struct ListNode*)malloc(sizeof(ListNode)); greaterhead = (struct ListNode*)malloc(sizeof(ListNode)); lesstail = lesshead; greatertail = greaterhead; while(cur) { if(cur->val < x) { lesstail->next = cur; lesstail = lesstail->next; } else { greatertail->next = cur; greatertail = greatertail->next; } cur = cur->next; } lesstail->next = greaterhead->next; greatertail->next = NULL; phead = lesshead->next; free(lesshead); free(greaterhead); return phead; } };