/**
* @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;
}
}
牛客网:划分链表
最新推荐文章于 2025-04-22 15:38:43 发布

2万+

被折叠的 条评论
为什么被折叠?



