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

leetcode 刷题之路 82 Partition List

时间:2014-08-13 15:02:26      阅读:208      评论:0      收藏:0      [点我收藏+]

标签:des   style   color   使用   os   io   数据   for   

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.

将链表中值小于某个数的节点移动到前半部分,/**
 * 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* dummyHead1=new ListNode(0);
        ListNode* dummyHead2=new ListNode(0);
        ListNode *p=dummyHead1,*q=dummyHead2;
        while(head!=NULL)
        {
            if(head->val<x)
            {
                p->next=head;
                head=head->next;
                p=p->next;
            }
            else
            {
                q->next=head;
                head=head->next;
                q=q->next;
            }
        }
        p->next=NULL;
        q->next=NULL;
        p->next=dummyHead2->next;
        p=dummyHead1->next;
        delete dummyHead1;
        delete dummyHead2;
        return p;
    }
划分链表,使得值小于某个数的节点都位于链表的前半部分,大于等于这个数的节点位于链表后半部分,且每部分的节点相对顺序保持不变。

方便起见,使用两个辅助头结点dummyHead1,dummyHead2作为两个链表的头结点,分别存储值小于给定数据的节点和值大于等于给定数据的节点,遍历原链表,根据链表节点值大小比较结果将节点移动到这两个辅助头结点表示的某一个链表中,最后再将两个链表头尾相连拼接即可。

代码如下:

/**
 * 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* dummyHead1=new ListNode(0);
        ListNode* dummyHead2=new ListNode(0);
        ListNode *p=dummyHead1,*q=dummyHead2;
        while(head!=NULL)
        {
            if(head->val<x)
            {
                p->next=head;
                head=head->next;
                p=p->next;
            }
            else
            {
                q->next=head;
                head=head->next;
                q=q->next;
            }
        }
        p->next=NULL;
        q->next=NULL;
        p->next=dummyHead2->next;
        p=dummyHead1->next;
        delete dummyHead1;
        delete dummyHead2;
        return p;
    }
};


leetcode 刷题之路 82 Partition List,布布扣,bubuko.com

leetcode 刷题之路 82 Partition List

标签:des   style   color   使用   os   io   数据   for   

原文地址:http://blog.csdn.net/u013140542/article/details/38535393

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