题解 | #链表分割#
链表分割
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) { struct ListNode* newhead, *newtail,*oldhead, *oldtail; newhead = newtail = (struct ListNode*)malloc(sizeof(struct ListNode)); oldhead = oldtail = (struct ListNode*)malloc(sizeof(struct ListNode)); struct ListNode* cur = pHead; while(cur) { if(cur->val < x) { newtail->next = cur; newtail = cur; cur = cur->next; } else { oldtail->next = cur; oldtail = cur; cur = cur->next; } } newtail->next = oldhead->next; oldtail->next = NULL; return newhead->next; } };