题目传送:​​https://leetcode.cn/problems/partition-list/​

运行效率

Leetcode86. 分隔链表_链表


代码如下:

/**
* 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 static ListNode partition(ListNode head, int x) {
ListNode smallerHead = new ListNode();
ListNode smaller = smallerHead;
ListNode biggerHead = new ListNode(); //这个头结点存在的意义就是 后期会把small链表和bigger链表进行连接,那个时候就会用到这个头结点
ListNode bigger = biggerHead;
//只要head不为null, 那就必定存在head.next
while (head!= null) {
if (head.val < x) {
smaller.next = head;
smaller=smaller.next;
} else {
bigger.next = head;
bigger= bigger.next;
}
head = head.next;
}
//遍历结束后,我们将large 的 next 指针置空,这是因为当前节点复用的是原链表的节点,而其next指针可能指向一个小于 x 的节点,
// 而那个小于x的节点最后会存进smaller里面,然后smaller的尾指针再和bigger头指针相接,最后容易产生环形链表, 所以我们需要切断这个引用
bigger.next=null;
smaller.next = biggerHead.next;
return smallerHead.next;
}
}