需求分析:
将链表分为两个部分在X前是小于X的,在X后是大于X的。只需要分割不需要排序。
实现思路:
通过从头节点开始遍历,判断小于X的放入一条链表种,大于X的放入另一个链表中,最后将两条链表相连,X置于两条链表相连的中点,如果链表中没有X则添加一个X节点。
实现方法:
/**
* 链表的分割
* @param node 传入头节点
* @param x 分割数
* @return
*/
public static Node partition(Node node, int x) {
Node linked1 = new Node(0);
Node linked2 = new Node(0);
Node curr1 = linked1;
Node curr2 = linked2;
Node head = node;
Node nodeX = null;
while (head != null) {
if (head.val < x) {
curr1.next = head;
curr1 = curr1.next;
} else if (head.val > x) {
curr2.next = head;
curr2 = curr2.next;
} else {
nodeX = head;
}
head = head.next;
}if (nodeX==null){
nodeX=new Node(4);
}
curr1.next = nodeX;
nodeX.next = linked2.next;
curr2.next = null;
return linked1.next;
}
//链表的节点类
public static class Node {
private int val;
private Node next;
public Node(int val) {
this.val = val;
}
}
测试:
public static void main(String[] args) {
Node node1 = new Node(1);
Node node2 = new Node(3);
Node node3 = new Node(5);
Node node4 = new Node(7);
Node node5 = new Node(6);
Node node6 = new Node(4);
Node node7 = new Node(2);
node1.next = node2;
node2.next = node3;
node3.next = node4;
node4.next = node5;
node5.next = node6;
node6.next = node7;
System.out.print("分割前:");
Node head1 =node1;
while (head1 != null) {
System.out.print(head1.val);
head1 = head1.next;
}
System.out.println();
System.out.print("分割后:");
Node head2 = partition(node1, 4);
while (head2 != null) {
System.out.print(head2.val);
head2 = head2.next;
}
}
测试结果: