- 问题描述
将单向链表按某值划分成左边小,中间相等、右边大的形式。
- 解决方案1
将单链表转换成数组,然后按照数组的方式进行partion分组,小的在头,大的在尾。注意这种方法会改变原来链表中数据的相对顺序。
/**
* 将单链表转换成数组,然后进行partion分组,小的在头,大的在尾
* @param head
* @param standard
*/
public static Node partionLinkedList1(Node head,Node standard){
if(head == null)
return null;
Node cur = head;
int len = 0;
while(cur != null){
len ++;
cur = cur.next;
}
Node[] arr = new Node[len];
cur = head;
int index = 0;
while(cur != null){
arr[index] = cur;
cur = cur.next;
index ++;
}
//数组partion过程
int small = -1;
int big = len;
for(int i = 0;i < big;i ++){
if(arr[i].value < standard.value){
small ++;
Node temp = arr[i];
arr[i] = arr[small];
arr[small] = temp;
}
else if(arr[i].value > standard.value){
big --;
Node temp = arr[i];
arr[i] = arr[big];
arr[big] = temp;
i --;
}
}
Node res = arr[0];
for(int i = 0;i < len - 1;i ++){
arr[i].next = arr[i + 1];
}
arr[len - 1].next = null;
return res;
}
- 解决方案2
将将单链表拆成比比较值小的small链表,相等的equal链表和大的big链表,然后将三个链表进行合并,注意边界条件,链表是否为空。这种方法不会改变原来链表中数据的相对顺序。
/**
* 将单链表拆成small,equal,big三个链表,然后将三个链表进行合并
* @param head
* @param standard
*/
public static Node partionLinkedList2(Node head,Node standard){
if(head == null)
return null;
Node small = new Node();
Node smallTail = small;
Node equal = new Node();
Node equalTail = equal;
Node big = new Node();
Node bigTail = big;
Node cur = head;
while(cur != null){
if(cur.value < standard.value){
smallTail.next = cur;
smallTail = smallTail.next;
}
else if(cur.value > standard.value){
bigTail.next = cur;
bigTail = bigTail.next;
}
else{
equalTail.next = cur;
equalTail = equalTail.next;
}
cur = cur.next;
}
smallTail.next = equal;
equalTail.next = big;
cur = small;
//删去equal和big节点
while(cur != null){
if(cur.next == big || cur.next == equal){
cur.next = cur.next.next;//删去哨兵节点
}
else
cur = cur.next;
}
//返回small.next,跳过small节点
return small.next;
}