首页 > 其他 > 详细

LeetCode之Partition List

时间:2014-01-28 23:47:24      阅读:518      评论:0      收藏:0      [点我收藏+]

【题目】

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的所有节点来到大于或等于x的所有节点之前。 
你应该保持在每两个分区的节点的原始相对顺序。

【分析】

【代码】

/*********************************
*   日期:2014-01-28
*   作者:SJF0115
*   题号: Partition List
*   来源:http://oj.leetcode.com/problems/partition-list/
*   结果:AC
*   来源:LeetCode
*   总结:
**********************************/
#include <iostream>
#include <stdio.h>
#include <algorithm>
using namespace std;

struct ListNode {
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};

class Solution {
public:
    ListNode *partition(ListNode *head, int x) {
        ListNode *leftHead = (ListNode*)malloc(sizeof(ListNode));
        ListNode *rightHead = (ListNode*)malloc(sizeof(ListNode));
        ListNode *lpre = leftHead,*rpre = rightHead;
        while(head != NULL){
            if(head->val < x){
                lpre->next = head;
                lpre = head;
            }
            else{
                rpre->next = head;
                rpre = head;
            }
            head = head->next;
        }
        rpre->next = NULL;
        lpre->next = rightHead->next;
        return leftHead->next;
    }
};
int main() {
    Solution solution;
    int A[] = {1,3,2};
    ListNode *head = (ListNode*)malloc(sizeof(ListNode));
    head->next = NULL;
    ListNode *node;
    ListNode *pre = head;
    for(int i = 0;i < 3;i++){
        node = (ListNode*)malloc(sizeof(ListNode));
        node->val = A[i];
        node->next = NULL;
        pre->next = node;
        pre = node;
    }
    head = solution.partition(head->next,5);
    while(head != NULL){
        printf("%d ",head->val);
        head = head->next;
    }
    return 0;
}






LeetCode之Partition List

原文:http://blog.csdn.net/sunnyyoona/article/details/18840809

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!