LeetCode 86 questions

Given a head node head of a linked list and a specific value x, please divide the linked list so that all nodes less than x appear before nodes greater than or equal to x. You should preserve the initial relative position of each node in the two partitions.

Example 1:
Input: head = [1,4,3,2,5,2], x = 3
Output: [1,2,2,4,3,5]

Source: LeetCode
Link: https://leetcode.cn/problems/partition-list

Idea: Create two new linked lists, one is used to store values ​​smaller than x, and the other is used to store values ​​greater than xde; each new linked list opens up two new node pointers Tail, Head, which means it is used to point to the head and tail of the table; Head Stand still there so that the new linked list Tail will be updated continuously

Note: To prevent the linked list from looping, for example: the original linked list is 1->4->3->2->5->2->NULL and the given value is 3

lessHead:1->2->2->NULL

greaterHead:4->3->5->NULL

The new linked list should be: 1->2->2->4->3->5->NULL Here, if the next field of 5 is not empty, then its next still points to 2 pointed to by the original linked list, and in The next field of 2 in the new linked list points to 4 so that a cycle is formed, which will lead to a crash

struct ListNode* partition(struct ListNode* head, int x)
{
struct ListNode*cur;
struct ListNode*lessTail;
struct ListNode*lessHead;
struct ListNode*greaterTail;
struct ListNode*greaterHead;
lessTail=lessHead=(struct ListNode*)malloc(sizeof(struct ListNode));
lessTail->next=NULL;
greaterTail=greaterHead=(struct ListNode*)malloc(sizeof(struct ListNode));
greaterTail->next=NULL;
cur=head;//开创一个哨兵结点
while(cur)
{
    if(cur->val<x)//将原链表小于x的值尾插进lessTail
    {
        lessTail->next=cur;
        lessTail=cur;//尾插值在不断更新
    }
    else
    {
        greaterTail->next=cur;//将大于x的数据尾插在greaterTail后面
        greaterTail=cur;
    }
    cur=cur->next;//在cur不为空的情况下执行完上面判断
    
}
lessTail->next=greaterHead->next;//存放值大于x的整体链表插入到存放值小于x的链表后面
greaterTail->next=NULL;//将新链表表尾置空,不然若新链表表尾元素在原链表不是表尾,新链表表尾它的next就会指向那个值形成循环链表
struct ListNode*pre=lessHead->next;//销毁开辟出来的新节点
free(lessHead);//释放
free(greaterHead);//释放

return pre;//返回新链表
}

Due to the limited ability of the editor, if there are any deficiencies in this article, please correct me in the comment area. Secondly, because it is the first time to write a blog, I am not proficient in typesetting, please forgive me

おすすめ

転載: blog.csdn.net/m0_67768006/article/details/127592024