[C语言][LeetCode][86]Partition List

来源:互联网 发布:云计算的未来发展趋势 编辑:程序博客网 时间:2024/06/06 11:40

题目

Partition List
Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.

You should preserve the original relative order of the nodes in each of the two partitions.

For example,
Given 1->4->3->2->5->2 and x = 3,
return 1->2->2->4->3->5.

标签

Linked List、Two Pointers

难度

中等

分析

题目意思是给定一个value,将单链表里比value小的放在左侧,大于或等于value的放到右侧,最后返回链表。我的做法是比value小的拼成一个链表,其他的拼成另一个链表,再将两个链表连接起来。

C代码实现

struct ListNode* partition(struct ListNode* head, int x) {    struct ListNode *leftHead, *rightHead, *left, *right;    struct ListNode *ret;    if(!head)        return NULL;    leftHead = (struct ListNode *)malloc(sizeof(struct ListNode));    rightHead = (struct ListNode *)malloc(sizeof(struct ListNode));    left = leftHead;    right = rightHead;    while(head)    {        if(head->val < x)        {            left->next = head;            left = left->next;        }        else        {            right->next = head;            right = right->next;        }        head = head->next;    }    right->next = NULL;    left->next = rightHead->next;    ret = leftHead->next;    if(leftHead)        free(leftHead);    if(rightHead)        free(rightHead);    return ret;}
0 0
原创粉丝点击