/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode partition(ListNode head, int x) {
if(head == null) return head;
ListNode low = new ListNode(0);
low.next = head;
ListNode high = new ListNode(0);
high.next = head;
ListNode temp1 = low;//把小于x的写在low里
ListNode temp2 = high;//把大于x的写在high里
while(head != null) {
if(head.val < x) {
temp1.next = head;
temp1 = temp1.next;
head = head.next;
} else {
temp2.next = head;
temp2 = temp2.next;
head = head.next;
}
}
temp2.next = null;//再把low和high连起来 low的尾巴连在high的头 但需要注意的是 high的尾巴要链到null 避免死循环
temp1.next = high.next;
return low.next;
}
}
Partition List
最新推荐文章于 2020-11-07 16:10:04 发布