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.
Example:
Input: head = 1->4->3->2->5->2, x = 3
Output: 1->2->2->4->3->5
自己的代码:
自己没有做出来,因为始终在想着怎么在原list上比较,调换大于x和小于x的节点的前后顺序;
别人的代码:
Runtime: 0 ms, faster than 100.00% of Java online submissions for Partition List.
Memory Usage: 37.1 MB, less than 5.32% of Java online submissions for Partition List.
核心思想
使用两个队列:一个用来连接所有小于x的节点;另一个存所有大于x的节点;最后将两个队列进行拼接;Remember to set the tail of second queue a null next, or u will get TLE.
public ListNode partition(ListNode head, int x) {
ListNode smallerHead = new ListNode(0), greaterHead = new ListNode(0); //dummy heads of the 1st and 2nd queues
ListNode smallerLast = smallerHead, greaterLast = greaterHead; //current tails of the two queues;
while (head != null){
if (head.val < x) {
smallerLast.next = head;
smallerLast = smallerLast.next;
}else {
greaterLast.next = head;
greaterLast = greaterLast.next;
}
head = head.next;
}
greaterLast.next = null; // 置null
smallerLast.next = greaterHead.next; //Skipping dummy head of greater and linking
return smallerHead.next; //Skipping dummy head of smaller and returning next
}
Python版本:
class ListNode(object):
def __init__(self,x):
self.val = x
self.next = None
class Solution(object):
def partition(self, head, x):
"""
:type head: ListNode
:type x: int
:rtype: ListNode
"""
smaller_head = ListNode(None)
greater_head = ListNode(None)
smaller_tail = smaller_head
greater_tail = greater_head
while head:
if head.val < x:
smaller_tail.next = head
smaller_tail = smaller_tail.next
else:
greater_tail.next = head
greater_tail = greater_tail.next
head = head.next
greater_tail.next = None
smaller_tail.next = greater_head.next
return smaller_head.next
测试:
if __name__ == "__main__":
print("---------")
a1 = ListNode(1)
a2 = ListNode(4)
a3 = ListNode(3)
a4 = ListNode(2)
a5 = ListNode(5)
a6 = ListNode(2)
x = 3
a1.next = a2
a2.next = a3
a3.next = a4
a4.next = a5
a5.next = a6
s = Solution()
head = s.partition(a1,x)
while head:
print(head.val)
head = head.next
print("---------++")