题目:
给定一个链表和一个特定值 x,对链表进行分隔,使得所有小于 x 的节点都在大于或等于 x 的节点之前。
你应当保留两个分区中每个节点的初始相对位置。
示例:
输入: head = 1->4->3->2->5->2, x = 3 输出: 1->2->2->4->3->5
思路:原文链接:https://blog.csdn.net/mine_song/article/details/70545448
以下代码的基本思想是将比给定值小的节点保存在一个链表中,将剩余节点保存在另外一个链表中。最后将这里两个链表链接起来。首先定义了两个链表的头节点,之后便利链表,进行判断。
代码:
class Solution {
public ListNode partition(ListNode head, int x) {
ListNode dummy1 = new ListNode(0); //链表开头两个空的节点
ListNode dummy2 = new ListNode(0);
// 当前结点
ListNode curr1 = dummy1;
ListNode curr2 = dummy2;
while (head != null) {
if (head.val < x) {
curr1.next = head;
curr1 = head;//curr1相当于一个指针,向后移动,方便添加
} else {
curr2.next = head;
curr2 = head;
}
head = head.next;
}
// important! avoid cycle in linked list.
// otherwise u will get TLE.
curr2.next = null;
curr1.next = dummy2.next;
return dummy1.next;//注意返回的是哪一个,curr1此时已经在链表的结尾部分
}
}
执行最快的代码:
思路基本上是一样的
class Solution {
public ListNode partition(ListNode head, int x) {
if (head == null) {
return null;
}
ListNode listNode1 = null;
ListNode listNode1Head = null;
ListNode listNode2 = null;
ListNode listNode2Head = null;
while (head != null) {
if (head.val >= x) {
if (listNode2 != null) {
listNode2.next = head;
listNode2 = listNode2.next;
} else {
listNode2Head = head;
listNode2 = head;
}
} else {
if (listNode1 != null) {
listNode1.next = head;
listNode1 = listNode1.next;
} else {
listNode1Head = head;
listNode1 = head;
}
}
head = head.next;
}
if (listNode2 != null) {
listNode2.next = null;
}
if (listNode1 != null) {
listNode1.next = listNode2Head;
} else {
return listNode2Head;
}
return listNode1Head;
}
}