划分链表
题目
解题思路
- Step1:将小于x和大于等于x的部分分别用头和尾指针创建链表
- Step2:将两个链表连接起来
代码实现及注释
class Solution {
/**
* Step1:将小于x和大于等于x的部分分别用头和尾指针创建链表
* Step2:将两个链表连接起来
*/
public static ListNode partition(ListNode head, int x) {
ListNode lefthead = null, lefttail = null;//小于x部分的头节点和尾节点
ListNode righthead = null,righttail = null;//小大于等于x部分的头节点和尾节点
ListNode next = null;//用于记录head的下一个节点(当把head加入新链表时需要将其head.next = null,如果不记录下一个节点,则无法继续进行遍历
while (head != null){
next = head.next;//将next记录呢需要的下一个节点
head.next = null;//将head与原来的链表断连
if (head.val<x){
if (lefthead == null){
lefthead = head;
lefttail = head;
}else {
lefttail.next = head;
lefttail = head;
}
}else {
if (righthead == null){
righthead = head;
righttail = head;
}else {
righttail.next = head;
righttail = head;
}
}
head = next;//将head移动到下一个节点
}
if (lefthead == null){//如果小于x的那部分链表为null
return righthead;//返回大于等于x那部分链表的头节点
}
if (lefthead!=null){//如果小于x的那部分链表不为null
lefttail.next = righthead;//将大于等于x那部分链表拼接到尾部
}
return lefthead;//返回链表头部
}
}