首页 > 其他 > 详细

leetcode笔记:Partition List

时间:2015-12-27 06:20:45      阅读:170      评论: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的前面,大于等于x的放到x的后面,每部分元素的原始相对位置不变。

该题是一个普通的链表遍历的题目,需要注意的地方在于必须将链表的最后一个节点的下一个节点更新为null,不然链表会出现环,从而导致死循环的情况。

三. 示例代码

#include <iostream>

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


class Solution
{
public:
    ListNode *partition(ListNode *head, int x)
    {
        ListNode *LessHeader = new ListNode(10);
        ListNode *LessTail = LessHeader;

        ListNode *GreaterHeader = new ListNode(10);
        ListNode *GreaterTail = GreaterHeader;

        while(head != NULL)
        {
            if (head->val < x)
            {
                LessTail->next = head;
                LessTail = head;
            }
            else
            {
                GreaterTail->next = head;
                GreaterTail = head;
            }

            head = head->next;
        }

        LessTail->next = GreaterHeader->next;
        GreaterTail->next = NULL;
        delete GreaterHeader;

        head = LessHeader->next;
        delete LessHeader;

        return head;
    }
};

四. 小结

leetcode笔记:Partition List

原文:http://blog.csdn.net/liyuefeilong/article/details/50411200

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