題目描述
編寫代碼,以給定值x為基準(zhǔn)將鏈表分割成兩部分,所有小于x的結(jié)點(diǎn)排在大于或等于x的結(jié)點(diǎn)之前
給定一個(gè)鏈表的頭指針 ListNode* pHead,請(qǐng)返回重新排列后的鏈表的頭指針。注意:分割以后保持原來(lái)的數(shù)據(jù)順序不變。
public ListNode partition(ListNode pHead, int x) {
ListNode biggerStart=null;
ListNode biggerEnd=null;
ListNode smallerStart=null;
ListNode smallerEnd=null;
while(pHead != null){
if(pHead.val<x){
if(smallerStart == null){
smallerStart=new ListNode(pHead.val);
smallerEnd=smallerStart;
}else{
ListNode tmp=new ListNode(pHead.val);
smallerEnd.next=tmp;
smallerEnd=tmp;
}
}else{
if(biggerStart == null){
biggerStart=new ListNode(pHead.val);
biggerEnd=biggerStart;
}else{
ListNode tmp=new ListNode(pHead.val);
biggerEnd.next=tmp;
biggerEnd=tmp;
}
}
pHead=pHead.next;
}
if(biggerStart == null && smallerStart == null){
return null;
}
if(biggerStart == null){
return smallerStart;
}
if(smallerStart == null){
return biggerStart;
}
smallerEnd.next=biggerStart;
return smallerStart;
}
期間我遇到兩個(gè)問(wèn)題
1.值傳遞和引用傳遞的問(wèn)題 明明思路都是對(duì)的,但是在調(diào)試的時(shí)候出現(xiàn)了各種問(wèn)題,總結(jié)一句話,沒(méi)有new就引用傳遞,new過(guò)了就值傳遞了
2.邊緣情況沒(méi)有考慮,只有左邊或只有右邊沒(méi)有判空