Leetcode 86 Partition List

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
}
class Solution(object):
    def partition(self, head, x):
        p = head
        l1, l2 = ListNode(0), ListNode(0)
        c1, c2 = l1, l2
        while p:
            if p.val < x:
                c1.next = p
                c1 = c1.next
            else:
                c2.next = p
                c2 = c2.next
            p = p.next
        c1.next, c2.next = l2.next, None
        return l1.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
posted @ 2015-06-22 19:23  lilixu  阅读(131)  评论(0编辑  收藏  举报