题目描述
编写代码,以给定值x为基准将链表分割成两部分,所有小于x的结点排在大于或等于x的结点之前
给定一个链表的头指针 ListNode* pHead,请返回重新排列后的链表的头指针。注意:分割以后保持原来的数据顺序不变。
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;
}
期间我遇到两个问题
1.值传递和引用传递的问题 明明思路都是对的,但是在调试的时候出现了各种问题,总结一句话,没有new就引用传递,new过了就值传递了
2.边缘情况没有考虑,只有左边或只有右边没有判空