《程式員面試金典》鏈表分割,《程式員面試金典》

來源:互聯網
上載者:User

《程式員面試金典》鏈表分割,《程式員面試金典》

【 聲明:著作權,轉載請標明出處,請勿用於商業用途。  聯絡信箱: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;        }};


著作權聲明:本文為博主原創文章,如果轉載,請註明出處

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.