题目来源
https://www.nowcoder.com/practice/0e27e0b064de4eacac178676ef9c9d70?tpId
题目描述
编写代码,以给定值x为基准将链表分割成两部分,所有小于x的结点排在大于或等于x的结点之前
给定一个链表的头指针 ListNode* pHead,请返回重新排列后的链表的头指针。注意:分割以后保持原来的数据顺序不变。
示例:以5为分割点
未分割前:11->2->7->5->4->3
分割完成后:2->4->3->11->7->5
解题思路
- 将比
x
小的放在一个链表,比x
大的放在另一个链表。最后将大的链表拼在小的链表后面
两种解法
解法1
-
不把原链表的
next
节点置空
这样做需要在最后把比x
大的链表的最后一个节点的next
置空 -
产生标志性头节点 最后返回的是标志头节点的
next
节点
解法2
- 将原链表
next
置空 - 不产生标志头节点,最后返回的是
smallHead
图解
解法1
- 初始链表
- 分割链表
*分割后再拼起来
注:cur2.next
最后一定要置空
解法2
- 初始链表
- 分割链表
- 分割后再拼接
实现代码
解法1
public ListNode partition(ListNode pHead, int x) {
ListNode cur = pHead;
//1.校验数据合法性
if (pHead == null || x < 0) {
return null;
}
//beforeXHead放比x小的节点 beforeXTail
//newHead2放比x大的节点
ListNode newHead1 = new ListNode(-1);
ListNode newHead2 = new ListNode(-1);
ListNode cur1 = newHead1;
ListNode cur2 = newHead2;
while (cur != null) {
if (cur.val < x) {
cur1.next = cur;
cur1 =cur1.next;
} else {
cur2.next = cur;
cur2 =cur2.next;
}
cur = cur.next;
}
cur2.next = null;
cur1.next = newHead2.next;
return newHead1.next;
}
解法2
public ListNode partition2(ListNode pHead, int x) {
//1.合法性校验
if (pHead == null || x < 0) {
return null;
}
//2.将小于X的放在一个新链表,将大于X的放在另一个新链表。然后把大于的串在小于的后面
ListNode smallHead = null;
ListNode smallTail = null;
ListNode bigHead = null;
ListNode bigTail = null;
while (pHead != null) {
ListNode nextNode = pHead.next;
pHead.next =null;
if (pHead.val < x) {
//判断是否是第一次插入
if (smallHead == null) {
smallHead = pHead;
smallTail =smallHead;
} else {
smallTail.next = pHead;
smallTail =smallTail.next;
}
} else {
if (bigHead == null) {
bigHead = pHead;
bigTail =bigHead;
} else {
bigTail.next = pHead;
bigTail = bigTail.next;
}
}
pHead = nextNode;
}
if (smallHead == null) {
return bigHead;
}
smallTail.next = bigHead; //两个链表头尾拼接
return smallHead;
}