《程序员面试金典》链表分割

来源:互联网 发布:网络语973什么意思 编辑:程序博客网 时间:2024/04/30 02:40

【 声明:版权所有,转载请标明出处,请勿用于商业用途。  联系信箱: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;        }};


0 0