分隔链表(中等)

分隔链表(中等)_第1张图片

维护两个链表 small 和 large 即可,small 链表按顺序存储所有小于 x 的节点,large 链表按顺序存储所有大于等于 x 的节点。遍历完原链表后,我们只要将 small 链表尾节点指向 large 链表的头节点即能完成对链表的分隔。

/**
 * 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) {
       ListNode samllhead=new ListNode(0);
       ListNode small=samllhead;
       ListNode largehead=new ListNode(0);
       ListNode large=largehead;
       while(head!=null){
        if(head.val

你可能感兴趣的:(链表,数据结构)