题目链接:https://leetcode-cn.com/problems/partition-list/
题目如下:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode partition(ListNode head, int x) {
// 思路:分成两个链表small和large,再合并起来
// smaller和bigger为实际工作指针,head1和head2为总头,代表整个链表
ListNode smaller=new ListNode(0);
ListNode bigger=new ListNode(0);
ListNode head1=smaller,head2=bigger;
while(head!=null){
if(head.val<x){
smaller.next=head;
smaller=smaller.next;
}else{
bigger.next=head;
bigger=bigger.next;
}
head=head.next;
}
bigger.next=null;
smaller.next=head2.next;
return head1.next;
}
}