题目链接
链接: 链表分割
题目要求
现有一链表的头指针 ListNode* pHead,给一定值x,编写一段代码将所有小于x的结点排在其余结点之前,且不能改变原来的数据顺序,返回重新排列后的链表的头指针。
解题思路
- 准备
2个空链表 :
small: 存放小于x的节点
large: 存放 大于等于x的节点 - 遍历原链表,比较链表的值和
x的大小关系 - 将
small和large拼接到一起,返回拼接链表
注意特殊情况:
small 为空 :所有的链表节点 都 >= x
large 为空 :所有的链表节点 都 < x
以及 small 和 large 的边界情况 —— 即是不是 null 结尾
代码实现
public class Partition {
public ListNode partition(ListNode pHead, int x) {
if(pHead == null){
return null;
}
//只有一个节点
if(pHead.next == null){
return pHead;
}
ListNode small = new ListNode(-1);
ListNode large = new ListNode(-1);
ListNode end1 = small;
ListNode end2 = large;
ListNode cur = pHead;
while(cur != null){
if(cur.val < x){
end1.next = cur;
end1 = cur;
}else{
end2.next = cur;
end2 = cur;
}
cur = cur.next;
}
small = small.next;
large = large.next;
//分别给samll large 的结尾添加 null
end1.next = end2.next = null;
//处理全都是 >= x 的情况 避免空指针异常
if(small == null){
return large;
}
end1.next = large;
return small;
}
}

824

被折叠的 条评论
为什么被折叠?



