题目
给你一个链表的头节点 head 和一个特定值 x ,请你对链表进行分隔,使得所有 小于 x 的节点都出现在 大于或等于 x 的节点之前。
你应当 保留 两个分区中每个节点的初始相对位置。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/partition-list
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路:小的放左边,大的放右边,有点像插入排序,那我们只需要维护两个链表,一个链表是小于给定的val值,另一个链表则是大于给定val值,最后将两个链表拼接即可。
//86. 分隔链表
/*
给你一个链表的头节点 head 和一个特定值 x ,
请你对链表进行分隔,使得所有 小于 x 的节点都出现在 大于或等于 x 的节点之前。
*/
public class Leetcode86 {
public ListNode partition(ListNode head, int x) {
ListNode temp1 = new ListNode(0);
ListNode result = temp1;
ListNode temp2 = new ListNode(0);
ListNode temp3 = temp2;
while(head!=null){
if(head.val<x){
temp1.next = head;
temp1 = temp1.next;
}else {
temp2.next = head;
temp2 = temp2.next;
}
head = head.next;
}
temp2.next = null;
temp1.next = temp3.next;
return result.next;
}
}
过于直白此算法,所以就没有写注释
由于只遍历了一次链表,所以时间复杂度为O(n)