题解 | #链表分割#
链表分割
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) { if (!pHead) return NULL; ListNode* pNewHead1 = NULL;//指向小链表 ListNode* cur1 = NULL;//遍历小链表 ListNode* pNewHead2 = NULL;//指向大链表 ListNode* cur2 = NULL;//遍历大链表 ListNode* cur = pHead;//指向旧链表 while (cur)//遍历旧链表 { if (cur->val < x)//符合要求,尾插到NewHead1 { if (pNewHead1 == NULL)//新链表1为空 { cur1 = pNewHead1 = cur; } else//新链表不为空 { cur1->next = cur; cur1 = cur1->next; } } else//不符合要求,cur->next >= x,尾插到NewHead2 { if (pNewHead2 == NULL)//新链表2为空 { cur2 = pNewHead2 = cur; } else//新链表不为空 { cur2->next = cur; cur2 = cur2->next; } } cur = cur->next; } if (cur1 == NULL) return pNewHead2; if (cur2 == NULL) return pNewHead1; cur1->next = pNewHead2; cur2->next = NULL; return pNewHead1; } };
用的是无头单链表