Question 11 done by Nioke Online, title address: https://www.nowcoder.com/practice/0e27e0b064de4eacac178676ef9c9d70?tpId=8&tqId=11004&rp=1&ru=/ta/cracking-the-coding-interview&qru=/ta/cracking -the-coding-interview/question-ranking
Topic description:
Write code to split the linked list into two parts based on a given value x, and all nodes less than x are sorted before nodes greater than or equal to x. Given a linked list head pointer ListNode* pHead, return the head pointer of the rearranged linked list. Note: The original data order remains unchanged after splitting.
AC code, containing test data:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
struct ListNode {
int val;
struct ListNode* next;
ListNode(int x): val(x), next(NULL) {}
};
class Partition {
public:
ListNode* partition(ListNode* pHead, int x){
ListNode* fkrt1 = new ListNode(0);
ListNode* fkrt2 = new ListNode(0);
ListNode* pSmall = fkrt1;
ListNode* pGe = fkrt2;
while(pHead!=NULL){
if(pHead->val < x){
pSmall->next = pHead;
pSmall = pSmall->next;
}else{
pGe->next = pHead;
pGe = pGe->next;
}
pHead = pHead->next;
}
pSmall->next = fkrt2->next;
// 下面这行很容易漏掉。处理的是边界情况:最后一个大于阈值x的值,如果它不是链表末尾,
// 那么在返回结果后进行遍历时,链表就没有终止了,产生环。显然应该避免环。
pGe->next = NULL;
ListNode* res = fkrt1->next;
delete fkrt1;
delete fkrt2;
return res;
}
};
int main() {
//vector<int> vals = {1, 3, 5, 7, 9, 11, 2, 4, 6, 8, 10};
vector<int> vals = {6,7,8,9,10,11, 1,2,3,4,5};
vector<ListNode*> vl;
for(int i=0; i<vals.size(); i++){
vl.push_back(new ListNode(vals[i]));
if(i>0){
vl[i-1]->next = vl[i];
}
}
cout << "the original datums are:" << endl;
for(int i=0; i<vals.size(); i++){
cout << vals[i] << ",";
}
cout << endl;
ListNode* head = vl[0];
Partition p;
int x = 6;
ListNode* res = p.partition(head, x);
cout << "do splitting with thresh value = " << x << ", gains: " << endl;
while(res!=NULL){
cout << res->val << ",";
res = res->next;
}
cout << endl;
return 0;
}