/**
* 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) {
//小于x的结点的一个链表
ListNode small = new ListNode(0);
ListNode smallHead = small;
//大于等于x的结点的一个链表
ListNode large = new ListNode(0);
ListNode largeHead = large;
//当前结点
ListNode cur = head;
//对原链表进行分隔
while (cur != null) {
//如果当前结点的值小于x,那么将该结点加入到小链表中
if (cur.val < x) {
small.next = cur;
small = small.next;
}
//如果当前结点的值大于等于x,那么将该结点加入到大链表中
else {
large.next = cur;
large = large.next;
}
//对原链表遍历
cur = cur.next;
}
//对大小两个链表进行合并,链表的最后一个结点指向null
large.next = null;
small.next = largeHead.next;
return smallHead.next;
}
}
86.分隔链表
最新推荐文章于 2024-07-23 12:29:02 发布