标签:
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
标签:
原文地址:http://www.cnblogs.com/lilixu/p/4593702.html