题目出处
题目描述
个人解法
思路:
todo
代码示例:(Java)
todo
复杂度分析
todo
官方解法
方法1:模拟
思路:
代码示例:(Java)
@Data
class ListNode {
int val;
ListNode next;
ListNode() {
}
ListNode(int val) {
this.val = val;
}
ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
}
public class Solution1 {
public ListNode partition(ListNode head, int x) {
ListNode small = new ListNode(0);
ListNode smallHead = small;
ListNode large = new ListNode(0);
ListNode largeHead = large;
while (head != null) {
if (head.val < x) {
small.next = head;
small = small.next;
} else {
large.next = head;
large = large.next;
}
head = head.next;
}
large.next = null;
small.next = largeHead.next;
return smallHead.next;
}
}
复杂度分析
- 时间复杂度: O(n),其中 n 是原链表的长度。我们对该链表进行了一次遍历。
- 空间复杂度: O(1)。