码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode No86. Partition List

时间:2016-08-07 21:52:42      阅读:178      评论:0      收藏:0      [点我收藏+]

标签:

Question:

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的放后面

Algorithm:

新建两个链表分别存放小于x的节点和大于等于x的节点。

Accepted Code:

/**
 * 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) {
        ListNode* head1=new ListNode(0);     //这样不用在while里面判断是否为头节点
        ListNode* head2=new ListNode(0);
        ListNode* l1=head1;
        ListNode* l2=head2;
        ListNode* p=head;
        while(p!=NULL)
        {
            if(p->val<x)
            {
                l1->next=p;
                l1=l1->next;
            }
            else
            {
                l2->next=p;
                l2=l2->next;
            }
            p=p->next;
        }
        l2->next=NULL;
        l1->next=head2->next;
        return head1->next;
    }
};



leetcode No86. Partition List

标签:

原文地址:http://blog.csdn.net/u011391629/article/details/52142802

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!