Solution1
链表问题要学会利用头结点,返回时把头结点去掉即可,代码比较简练。
参考网址:https://www.nowcoder.com/profile/188146/codeBookDetail?submissionId=13970528
/*
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
if (!pHead) {
return nullptr;
}//if
ListNode *smallList = new ListNode(-1);
ListNode *bigList = new ListNode(-1);
ListNode *ps = smallList,*pb = bigList,*cur = pHead;
while (cur) {
if (cur->val < x) {
ps->next = cur;
ps = ps->next;
}//if
else{
pb->next = cur;
pb = pb->next;
}//else
cur = cur->next;
}//while
pb->next = nullptr;
ps->next = bigList->next;
return smallList->next;
}
};