Description
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:
1 | Input: head = 1->4->3->2->5->2, x = 3 |
解法
这道题可以将所有小于给定值的节点取出组成一个新的链表,并在原表中删除,此时原链表中剩余的节点的值都大于或等于给定值,只要将原链表直接接在新链表后即可。
对于输入 1 -> 4 -> 3 -> 2 -> 5 -> 2 ,3
此种解法链表变化顺序为:
Original: 1 -> 4 -> 3 -> 2 -> 5 -> 2
New:
Original: 4 -> 3 -> 2 -> 5 -> 2
New: 1
Original: 4 -> 3 -> 5 -> 2
New: 1 -> 2
Original: 4 -> 3 -> 5
New: 1 -> 2 -> 2
Original:
New: 1 -> 2 -> 2 -> 4 -> 3 -> 5
具体代码如下:
1 | class Solution { |