86. Partition List

来源:互联网 发布:手机怎么设置4g网络 编辑:程序博客网 时间:2024/06/01 08:44

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.

思路:开始想着如何在一个链表上实现,后来参考别人的发现没有必要,重新建两个链表就可以了,一个存大的,一个存小的。或者重新建一个新的,另外一个在原来的基础上删除。

还有一种思路是找到第一个大于等于x的,对于后面所有的小于x都插到它前面。

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public:    ListNode* partition(ListNode* head, int x) {        if(head==NULL || head->next==NULL)        {            return head;        }        ListNode* bigList = new ListNode(-1);        ListNode* fakeHead = new ListNode(-1);        fakeHead->next = head;        ListNode* pre = fakeHead;        ListNode* preBig = bigList;        while(head!=NULL)        {            if(head->val >= x)            {                pre->next = head->next;                preBig->next = head;                preBig = preBig->next;                preBig->next = NULL;                head = pre->next;            }            else            {                pre = pre->next;                head = head->next;            }        }        preBig->next = NULL;        pre->next = bigList->next;        return fakeHead->next;    }};
0 0
原创粉丝点击