链表分割

package 链表分割;

import java.util.*;

class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}

public class Partition {

    public ListNode partition(ListNode head, int x) {
        ListNode pHead = new ListNode(-1);
        ListNode pHead2 = new ListNode(-2);
        // first list
        ListNode firstHead = pHead;
        ListNode firstTail = pHead;
        // second list
        ListNode secondTail = pHead2;
        ListNode secondHead = pHead2;
        //
        ListNode traverse = head;
        while (traverse != null) {
            int val = traverse.val;
            if (val < x) {
                firstTail.next = traverse;
                firstTail = firstTail.next;
                traverse = traverse.next;
                firstTail.next = null;
            } else {
                if (val >= x) {
                    secondTail.next = traverse;
                    secondTail = secondTail.next;
                    traverse = traverse.next;
                    secondTail.next = null;
                }
            }
        }
        firstTail.next = secondHead.next;
        return firstHead.next;
    }

    public static void main(String[] args) {
        ListNode head = new ListNode(1);
        ListNode head1 = new ListNode(2);
        ListNode head2 = new ListNode(3);
        ListNode head3 = new ListNode(4);
        ListNode head4 = new ListNode(5);
        ListNode head5 = new ListNode(6);
        head.next = head5;
        head5.next = head1;
        head1.next = head4;
        head4.next = head2;
        head2.next = head3;
        print(new Partition().partition(head, 3));
    }

    private static void print(ListNode head) {
        if(head == null){
            return ;
        } else {
            System.out.print(head.val + " ");
            print(head.next);
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值