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
这个题目就是利用两个dummy node,leftDummy 代表小于x的那些node,rightDummy 代表大于等于x的那些node,最后将两者加起来即可。
Code
class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def partitionList(self, head, x): leftDummy, rightDummy = ListNode(0), listNode(0) left, right = leftDummy, rightDummy while head: if head.val < x: left.next = head left = left.next else: right.next = head right = right.next head = head.next left.next = rightDummy.next right.next = None return leftDummy.next
原文地址:https://www.cnblogs.com/Johnsonxiong/p/10801691.html
时间: 2024-10-04 22:47:29