/* 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 ListNode* pFirst; ListNode* pHead1 = NULL; ListNode* pHead2 = NULL; ListNode* pBig = NULL; ListNode* pSmall = NULL; pFirst = pHead; for(pFirst; pFirst != NULL; pFirst = pFirst->next) { if((pFirst->val) < x) { if(pSmall == NULL) { pSmall = pFirst; //pSmall->val = pFirst->val;//值不需要赋给,直接存有的 pHead1 = pSmall; } else{ pSmall->next = pFirst; //pSmall->next->val = pFirst->val; pSmall = pFirst; //pSmall指向当前的pFirst,以便进行下一次循环 } } else{ if(pBig == NULL) { pBig = pFirst; //pBig->val = pFirst->val; pHead2 = pBig; } else{ pBig->next = pFirst; //pBig->next->val = pFirst->val; pBig = pFirst; } } } if(pSmall && pBig) {pBig->next = NULL; pSmall->next = pHead2; return pHead1;} else if(pSmall) {pSmall->next = NULL; return pHead1;} else {pBig->next = NULL; return pHead2;} ////写法1: //if(pBig) {pBig->next = NULL;} //需要将后面的给去掉 //if(pSmall){ pSmall->next = pHead2;return pHead1;} //else return pHead2; ////写法2: //if(pBig != NULL) pBig->next = NULL; //if(pSmall != NULL) {pSmall->next = pHead2;} //else{ pHead1 = pHead2; } //return pHead1; } };
这道题被折磨死了,整了好久一直编译通不过出问题,原因出在最后返回值那里。
1.最后一个链表末尾指针需要置NULL,不然总是出现程序打印过多数据。
2.后面的几种情况需要进行判断,应该可以优化写法。