86.分隔链表
这个题的意思比较简单就是要把小于x的放一边,大于x的放一边,我们可以把这一个链表分为大于 x,和小于 x 的两个链表,分开后只需要将小于 x 链表的最后一个结点的 next 指向大于 x 链表的头结点的 next 即可,最后将大于 x 链表的最后一个元素置为null即可
class Solution {
public ListNode partition(ListNode head, int x) {
ListNode lh = new ListNode(-1);
ListNode rh = new ListNode(-1);
ListNode lt = lh;
ListNode rt = rh;
/* for (ListNode p = head; p != null; p = p.next) {
if (p.val < x) {
lt.next = p;
lt = lt.next;
} else {
rt.next = p;
rt = rt.next;
}
} */
while (head != null) {
if (head.val < x) {
lt.next = head;
lt = lt.next;
} else {
rt.next = head;
rt = rt.next;
}
head = head.next;
}
lt.next = rh.next;
rt.next = null;
return lh.next;
}
}
标签:rt,head,ListNode,next,链表,lt,分隔
From: https://www.cnblogs.com/kingmc/p/16940520.html