【练习题】之以X为基准分割两个链表

    xiaoxiao2022-07-14  137

    编写代码,以给定的值x基准将链表分割成两部分,所有小于X的结点排在大于或等于X的结点之前。

    class Partition { public ListNode* partition(ListNode* pHead, int x) { // write code here if(NULL == pHead) return NULL; ListNode lessList(1); ListNode greaterList(1); ListNode* pTail1 = &lessList; ListNode* pTail2 = &greaterList; ListNode* pCur = pHead;//分割链表,从头部开始走 while(pCur) { if(pCur->val < x) { pTail1->next = pCur; pTail1 = pTail1->next; } else { pTail2->next = pCur; pTail2 = pTail2->next; } pCur = pCur->next; } pTail1->next = NULL; pTail2->next = NULL; pTail1->next = greaterList.next; return lessList.next; } };

     

     

     

     

     

     

     

     

    ~bye~ 

     

     

    最新回复(0)