《程式員面試金典》鏈表分割,《程式員面試金典》
【 聲明:著作權,轉載請標明出處,請勿用於商業用途。 聯絡信箱:libin493073668@sina.com】
題目連結:http://www.nowcoder.com/practice/0e27e0b064de4eacac178676ef9c9d70?rp=1&ru=/ta/cracking-the-coding-interview&qru=/ta/cracking-the-coding-interview/question-ranking
題目描述
編寫代碼,以給定值x為基準將鏈表分割成兩部分,所有小於x的結點排在大於或等於x的結點之前
給定一個鏈表的頭指標 ListNode* pHead,請返回重新排列後的鏈表的頭指標。注意:分割以後保持原來的資料順序不變。
思路
我們可以開兩個新的鏈表,一個small儲存比x小的結點,一個big儲存大於等於x的結點,最後再將兩個節點拼接起來即可
/*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==nullptr) return nullptr; ListNode *pNode = pHead; ListNode *small = new ListNode(0); ListNode *big = new ListNode(0); ListNode *ptr1 = small; ListNode *ptr2 = big; while(pNode) { if(pNode->val<x) { ptr1->next = pNode; pNode = pNode->next; ptr1 = ptr1->next; ptr1->next = nullptr; } else { ptr2->next = pNode; pNode = pNode->next; ptr2 = ptr2->next; ptr2->next = nullptr; } } ptr1->next = big->next; return small->next; }};
著作權聲明:本文為博主原創文章,如果轉載,請註明出處