LeetCode-Linked List Split

Linked list split

Title description

The existing head pointer ListNode*pHead of a linked list, given a certain value x, write a piece of code to arrange all nodes less than x before the rest of the nodes without changing the original data order, and return the head pointer of the rearranged linked list.

Example 1
Insert picture description here

Idea analysis

Open two new linked lists, put the nodes less than x into the first new linked list, put the nodes greater than x into the second new linked list, and then insert the end of the second new linked list into the first new linked list

The diagram is as follows:
Insert picture description here

Code

class Partition {
    
    
public:
    ListNode* partition(ListNode* pHead, int x) 
    {
    
    
        ListNode* cur = pHead;
        //小于x的节点放入链表newhead1
        ListNode* newhead1 = NULL;
        //大于x的节点放入链表newhead2
        ListNode* newhead2 = NULL;
        ListNode* tail1 = NULL;
        ListNode* tail2 = NULL;
        //开两段新空间
        newhead1 = tail1 = (ListNode*)malloc(sizeof(ListNode));
        newhead2 = tail2 = (ListNode*)malloc(sizeof(ListNode));
        //大于等于x放newhead2,小于x放newhead1
        while(cur)
        {
    
    
            if(cur->val >= x)
            {
    
    
                tail2->next = cur;
                tail2 = cur;
            }
            else
            {
    
    
                tail1->next = cur;
                tail1 = cur;
            }
            cur = cur->next;
        }
        //大于x链表尾插到小于x的链表后面
        tail1->next = newhead2->next;
        //让最后一个节点next指向空
        tail2->next = NULL;
        //保存链表头地址,防止释放空间找不到
        ListNode* tem = newhead1->next;
        //释放空间
        free(newhead1);
        free(newhead2);
        return tem;
    }
};

Guess you like

Origin blog.csdn.net/weixin_50886514/article/details/113483807