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

Leetcode 86 Partition List

时间:2015-06-22 20:38:42      阅读:156      评论: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放入两个链表,最后再串起两个链表即可。

var partition = function(head, x) {
    var c1 = new ListNode()
    var c2 = new ListNode()
    var h1 = c1
    var h2 = c2
    while(head){
        if(head.val < x){
            c1.next = head
            c1 = c1.next
            head = head.next
        }
        else{
            c2.next = head
            c2 = c2.next
            head = head.next
        }
    }
    c1.next = h2.next
    c2.next = null
    return h1.next
}

之前用的方法:扫描链表,如果小于x则直接移出置前,大于x不进行操作。

def partition(self, head, x):
    if not head:
        return None
    dy = ListNode(0)
    dy.next = head
    a = dy
    while a.next and a.next.val < x:
        a = a.next
    b = a.next
    c = b
    while c and c.next:
        if c.next.val < x:
            d = c.next
            c.next = c.next.next
            a.next = d
            d.next = b
            a = d
        else:
            c = c.next
    return dy.next

Leetcode 86 Partition List

标签:

原文地址:http://www.cnblogs.com/lilixu/p/4593702.html

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