/**前端
* 功能:以給定值x爲基準將鏈表分割成兩部分,全部小於x的結點排在大於或等於x的節點以前。java
*/node
兩種方法:直接建立兩個鏈表:一個鏈表存放小於x的元素,另外一個存放大於或等於x的元素。後端
一、方法一:插入後端函數
/* * 直接建立兩個鏈表:一個鏈表存放小於x的元素,另外一個存放大於或等於x的元素。 * 而後迭代訪問整個鏈表,將元素插入before或者after鏈表末尾。一旦抵達鏈表末端,則代表拆分完畢,最後合併兩個鏈表。 */ public static LinkedListNode partition(LinkedListNode node, int x){ if( node== null) return null; LinkedListNode beforeStart= null; LinkedListNode beforeEnd= null; LinkedListNode afterStart= null; LinkedListNode afterEnd= null; while( node!= null){ LinkedListNode next= node. next; //將鏈表存儲在next中 node. next= null; //將node的next清零表示,只是添加一個節點,而非以該節點爲頭結點的鏈表 if( node. data< x){ if( beforeStart== null){ beforeStart= node; beforeEnd= beforeStart; } else{ beforeEnd. next= node; beforeEnd= node; } } else{ if( afterStart== null){ afterStart= node; afterEnd= afterStart; } else{ afterEnd. next= node; afterEnd= node; } } node= next; } if( beforeStart== null) return afterStart; //合併 beforeEnd. next= afterStart; return beforeStart; }
二、方法二:插入前端this
/* * 直接建立兩個鏈表:一個鏈表存放小於x的元素,另外一個存放大於或等於x的元素。 * 而後迭代訪問整個鏈表,將元素插入before或者after鏈表前端!!!一旦抵達鏈表末端,則代表拆分完畢,最後合併兩個鏈表。 */ public static LinkedListNode partition2(LinkedListNode node, int x){ if( node== null) return null; LinkedListNode beforeStart= null; LinkedListNode afterStart= null; while( node!= null){ LinkedListNode next= node. next; node. next= null; if( node. data< x){ node. next= beforeStart; beforeStart= node; } else{ node. next= afterStart. next; afterStart= node; } } if( beforeStart== null) return afterStart; LinkedListNode head= beforeStart; while( beforeStart. next!= null){ beforeStart= beforeStart. next; } beforeStart. next= afterStart; return head; }
public class Partition {spa
public static ListNode partition(ListNode pHead, int x) {
if(pHead==null || pHead.next==null) //若是爲空,或者只有一個節點直接返回
return pHead;
ListNode maxHead = new ListNode(1);//定義大於等於的頭節點
ListNode minHead = new ListNode(0);//定義小於的頭節點
ListNode posMax = maxHead;//定義一個大於等於的鏈表 指針,指向當前位置
ListNode posMin = minHead;//定義一個小於的鏈表 指針,指向當前位置
while(pHead!=null)
{
while(pHead!=null&&pHead.val<x)
{
posMin.next = pHead;
posMin = posMin.next;//指針後移
pHead = pHead.next;
posMin.next = null;//斷開與下一位的鏈接
}
while(pHead!=null&&pHead.val>=x)//之因此判斷爲空是爲了不所有爲小於x時,執行到這再調用val會報空指針
{
posMax.next = pHead;
posMax = posMax.next;
pHead = pHead.next;
posMax.next = null;
}
}
if(minHead.next==null)
return maxHead.next;
if(maxHead.next!=null)
posMin.next = maxHead.next;
return minHead.next;
}
}指針
import
java.util.*;
code
/*
it
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) { //注意這裏有構造函數!!
this.val = val;
}
}*/
//思路:掃描兩邊遍,第一遍接小於x的,第二遍接大於等於x的
public
class
Partition {
public
ListNode partition(ListNode pHead,
int
x) {
ListNode head =
new
ListNode(-
1
);
//保留頭結點
ListNode p = pHead;
ListNode h = head;
while
(pHead !=
null
){
if
(pHead.val < x){
h.next =
new
ListNode(pHead.val);
//新建一個節點接在後面
h = h.next;
}
pHead = pHead.next;
}
while
(p !=
null
){
if
(p.val >= x){
h.next =
new
ListNode(p.val);
h = h.next;
}
p = p.next;
}
return
head.next;
}
}