2.4---把链表划分为两部分(CC150)

时间:2023-07-09 16:25:26

注意,题目要求要保持两部分的相对顺序,所以,用交换是不行的。

import java.util.HashSet;
import java.util.Set; class ListNode{
int val;
ListNode next;
ListNode(int x){
val = x;
}
} public class Solution{ public static void main(String[] args){
ListNode head = new ListNode(3);
head.val = 3;
ListNode node = new ListNode(1);
node.val = 1;
head.next = node;
ListNode tmp = head;
while(tmp != null){
System.out.println(tmp.val);
tmp = tmp.next;
}
tmp = partition(head,2);
System.out.println("delete"); while(tmp != null){ System.out.println(tmp.val);
tmp = tmp.next;
}
}
public static ListNode partition(ListNode head, int x) {
//思路:用两个链表记录一下两部分,然后合并
if(null == head)
return head;
ListNode greater = new ListNode(0);//小的
ListNode smaller = new ListNode(0);//>=
ListNode tmp1 = greater;
ListNode tmp2 = smaller; ListNode tmp = head;
while(tmp != null)
{
if(tmp.val < x)
{
ListNode n = new ListNode(tmp.val);
tmp2.next = n;
tmp2 = tmp2.next;//error: not write
}
else
{
ListNode m = new ListNode(tmp.val);
tmp1.next = m;
tmp1 = tmp1.next;//error: not write
}
tmp = tmp.next;//总是忘记写这一步
}
//最后合并
tmp1.next = null;
tmp2.next = greater.next;
return smaller.next;
}
}