86-partition list

来源:互联网 发布:数据录入查询系统源码 编辑:程序博客网 时间:2024/06/05 19:04

难度:medium
类别:linked list

1.题目描述

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.

2.算法分析

遍历一遍链表,将比x小的数值压到一个队列中,比x大或者等于x的压到另外一个队列中。
创建新的链表,从存小值的队列开始创建,创建完了以后再讲大值得队列中的值添加到新的链表中。

3.代码实现

ListNode* partition(ListNode* head, int x) {    if (head == NULL || head->next == NULL) return head;    queue<int> smaller, bigger;    while (head != NULL) {        if (head->val < x) {            smaller.push(head->val);        }        else {            bigger.push(head->val);        }        head = head->next;    }    ListNode* result = NULL;    if (!smaller.empty()) {        result = new ListNode(smaller.front());        head = result;        smaller.pop();    }    else {        result = new ListNode(bigger.front());        head = result;        bigger.pop();    }    while (!smaller.empty()) {        result->next = new ListNode(smaller.front());        smaller.pop();        result = result->next;    }    while (!bigger.empty()) {        result->next = new ListNode(bigger.front());        bigger.pop();        result = result->next;    }    return head;}
原创粉丝点击