partition list

来源:互联网 发布:网络十大禁书合集下载 编辑:程序博客网 时间:2024/06/01 08:39

题目:
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,
Given1->4->3->2->5->2and x = 3,
return1->2->2->4->3->5.

从头遍历链表,把值小于x的接到左链表中,大于等于x的放到右链表,最后连接左右链表class Solution{  public:    ListNode* partition(ListNode* head, int x)    {        if (head == NULL)            return NULL;        ListNode left_dummy(-1);        ListNode right_dummy(-1);        auto left_cur = &left_dummy;        auto right_cur = &right_dummy;        for(ListNode* cur = head; cur; cur = cur->next)        {            if (cur->val < x)            {                left_cur->next = cur;                left_cur = cur;            }            else            {                right_cur->next = cur;                right_cur = cur;            }        }        left_cur->next = right_dummy.next;        right_cur->next = NULL;        return left_dummy.next;    }};int main(){    ListNode* head =    CreateList();    PrintLinkList(head);    cout << "after partition: " << endl;    Solution tmp;    ListNode* after =   tmp.partition(head,3);    PrintLinkList(after);    return 0;}
0 0
原创粉丝点击