标签:排列 class desc ext work while nod tno strong
编写代码,以给定值x为基准将链表分割成两部分,所有小于x的结点排在大于或等于x的结点之前
给定一个链表的头指针 ListNode* pHead,请返回重新排列后的链表的头指针。注意:分割以后保持原来的数据顺序不变。
/* 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 || !pHead->next) return pHead; ListNode* littleBegin = new ListNode(-1); ListNode* bigBegin = new ListNode(-1); ListNode* little = littleBegin; ListNode* big = bigBegin; ListNode* pWork = pHead; while(pWork){ if(pWork->val < x){ little->next = pWork; little = little->next; }else{ big->next = pWork; big = big->next; } pWork = pWork->next; } little->next = bigBegin->next; big->next = nullptr; return littleBegin->next; } };
//思路为建立两个链表little中存放比x小的元素,big中存放比x大的元素。
//之后合并little和big两个链表。
标签:排列 class desc ext work while nod tno strong
原文地址:http://www.cnblogs.com/xiuxiu55/p/6657804.html