题目链接:力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台
解题思路:读了几遍才看懂什么意思。。。使用双指针进行解题,一趟遍历即可完成调整。时间复杂度为O(n)
- 如果head ==null || head.next == null,无需调整位置,直接返回head即可
- 设置一个哑元节点dumpy,令dumpy.next = head
- 双指针:
- prev:已经调整过位置的节点中小于x 的节点中最后一个节点,初始值指向dumpy,即头节点的前驱
- end:已经调整过位置的节点中大于等于x的节点中的最后一个节点,初始值为null
- 从前向后遍历链表,依次调整每一个节点的位置:
- 如果当前节点值比x小,就将其插入到pre节点后面,更新pre为新插入的节点
- 如果当前节点大于等于x,就将其插入到end节点后面,更新end=end.next
AC代码:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode partition(ListNode head, int x) {
if (head == null||head.next==null) {
return head;
}
ListNode dumpy = new ListNode();
dumpy.next = head;
ListNode pre = dumpy;
ListNode end = null;
while (head != null) {
if (head.val < x) {
ListNode tem = head;
head = head.next;
if (pre.next!=tem){
tem.next = pre.next;
}
pre.next = tem;
pre = pre.next;
} else {
if (end==null){
pre.next = head;
end= head;
head=head.next;
}else {
end.next = head;
end=end.next;
head=head.next;
}
}
}
if (end!=null){
end.next=null;
}
return dumpy.next;
}
}