分隔链表,给定一个链表和一个特定值 x,对链表进行分隔,使得所有小于 x 的节点都在大于或等于 x 的节点之前。你应当保留两个分区中每个节点的初始相对位置。Java实现

/**
 * 给定一个链表和一个特定值 x,对链表进行分隔,使得所有小于 x 的节点都在大于或等于 x 的节点之前。
 * 你应当保留两个分区中每个节点的初始相对位置。
 * 示例:
 * 输入: head = 1->4->3->2->5->2, x = 3
 * 输出: 1->2->2->4->3->5
 * 来源:力扣(LeetCode)
 * 链接:https://leetcode-cn.com/problems/partition-list
 */
public class Partition {

    public static ListNode partitionList(ListNode head, int value){
        //这里新建节点作为头节点,list1为链表的前半段用于存储小于value的值,
        // 而list2则用于存储大于等于x的值
        ListNode list = head;
        ListNode list1 = new ListNode(0);
        ListNode list2 = new ListNode(0);
        ListNode front = list1;
        ListNode rear = list2;
        while(list != null){
            //存入list1
            ListNode temp = list.next;
            if(list.val < value){
                list1.next = list;
                list1 = list1.next;
                list1.next = null;
                list = temp;
            }else{
                list2.next = list;
                list2 = list2.next;
                list2.next = null;
                list = temp;
            }
        }
        //合并链表
        ListNode node1 = front;

        while (node1.next != null){
            node1 = node1.next;
            if(node1.next == null){
                node1.next = rear.next;
                break;
            }
        }
        if(front.next == null){
            return rear.next;
        }else{
            return front.next;
        }
    }

    public static void main(String[] args){
        ListNode head = new ListNode(1);
        ListNode node1 = new ListNode(4);
        ListNode node2 = new ListNode(3);
        ListNode node3 = new ListNode(2);
        ListNode node4 = new ListNode(5);
        ListNode node5 = new ListNode(2);
        head.next = node1;
        node1.next = node2;
        node2.next = node3;
        node3.next = node4;
        node4.next = node5;
//        ListNode result = partitionList(head, 3);
        ListNode result = partitionList(head, 4);
        while (result != null){
            System.out.println(result.val);
            result = result.next;
        }
    }

}

class ListNode {
    int val;
    ListNode next;
    ListNode(int x) { val = x; }
}

当输入的值时3是结果如下

当输入的值是4时结果如下

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值