当前位置:网站首页>[cm11 linked list splitting]

[cm11 linked list splitting]

2022-06-22 21:06:00 Cat star people who love Durian


One 、 Title Description

The head pointer of an existing linked list ListNode pHead, Give a certain value x, Write a piece of code that will all be less than x The nodes of are arranged before the other nodes , And the original data order cannot be changed , Returns the head pointer of the rearranged linked list .

Topic link


Two 、 Provide easy to read code diagram

 Insert picture description here


3、 ... and 、 Title code

Tips : Pay attention to the dead cycle , Must put bigTail->next Set up NULL

/* struct ListNode { int val; struct ListNode *next; ListNode(int x) : val(x), next(NULL) {} };*/
class Partition {
    
public:
    ListNode* partition(ListNode* pHead, int x) {
    
        ListNode* smallHead=(ListNode*)malloc(sizeof( ListNode));
        smallHead->next=NULL;
        ListNode* bigHead=(ListNode*)malloc(sizeof( ListNode));
        bigHead->next=NULL;
        ListNode* cur,*bigTail,*smallTail;
        cur=pHead;
        smallTail=smallHead;
        bigTail=bigHead;
        while(cur)
        {
    
            if(cur->val<x)
            {
    
                smallTail->next=cur;
                smallTail=smallTail->next;
            }
            else
            {
    
                bigTail->next=cur;
                bigTail=bigTail->next;
            }
            cur=cur->next;
        }
        bigTail->next=NULL;
        smallTail->next=bigHead->next;
        ListNode* newHead=smallHead->next;
        free(smallHead);
        free(bigHead);
        return newHead;
    
    }
};

The above is the whole content of this article , If there are mistakes in the article or something you don't understand , Communicate more with meow bloggers . Learn from each other and make progress . If this article helps you , Can give meow bloggers a concern , Your support is my biggest motivation .

原网站

版权声明
本文为[Cat star people who love Durian]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/173/202206221941073923.html