/**
* @author xienl
* @description 划分链表
* @date 2022/7/4
*/
public class Solution {
public static void main(String[] args) {
Solution solution = new Solution();
ListNode listNode = new ListNode(1, new ListNode(4, new ListNode(3, new ListNode(2, new ListNode(5, new ListNode(2))))));
System.out.println(solution.partition(listNode, 3));
}
/**
* 双链表
* @param head
* @param x
* @return
*/
public ListNode partition (ListNode head, int x) {
// write code here
ListNode node1 = new ListNode(0);
ListNode node2 = new ListNode(0);
ListNode cur1 = node1;
ListNode cur2 = node2;
while (head != null){
if (head.val < x){
node1.next = head;
node1 = node1.next;
} else {
node2.next = head;
node2 = node2.next;
}
head = head.next;
}
node2.next = null;
node1.next = cur2.next;
return cur1.next;
}
}
class ListNode {
int val;
ListNode next = null;
public ListNode(int val) {
this.val = val;
}
public ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
}
02-05
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交