86. 分隔链表

作者: 王可尊 | 来源:发表于2019-01-17 00:32 被阅读0次

86. 分隔链表

问题

给定一个链表和一个特定值 x,对链表进行分隔,使得所有小于 x的节点都在大于或等于x的节点之前。

你应当保留两个分区中每个节点的初始相对位置。

示例:

输入: head = 1->4->3->2->5->2, x = 3
输出: 1->2->2->4->3->5

解法

新建两个dummyHead,其中一个保存所有小于x的节点,另一个保存所有大于等于x的节点。最后拼接两个链表就行了。

代码

java实现

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode partition(ListNode head, int x) {
        ListNode dummy1 = new ListNode(1);
        ListNode dummy2 = new ListNode(1);
        ListNode node1 = dummy1;
        ListNode node2 = dummy2;
        while(head != null) {
            if (head.val < x) {
                node1.next = head;
                head = head.next;
                node1 = node1.next;
                node1.next = null;
            } else {
                node2.next = head;
                head = head.next;
                node2 = node2.next;
                node2.next = null;
            }
        }
        node1.next = dummy2.next;
        return dummy1.next;
    }
}

整体也没什么难度。需要注意的就是在

相关文章

  • 86. 分隔链表

    86. 分隔链表[https://leetcode-cn.com/problems/partition-list/...

  • 86. 分隔链表

    86. 分隔链表[https://leetcode.cn/problems/partition-list/] 给你...

  • 力扣每日一题:86.分隔链表 创建大小链表与寻找第一个链表头两种

    86.分隔链表[https://leetcode-cn.com/problems/partition-list/s...

  • 86. 分隔链表

    86. 分隔链表 问题 给定一个链表和一个特定值 ,对链表进行分隔,使得所有小于 的节点都在大于或等于的节点之前。...

  • 86. 分隔链表

    双指针法: 直觉我们可以用两个指针pbig 和 psmall 来追踪上述的两个链表。两个指针可以用于分别创建两个链...

  • 86. 分隔链表

    原题 https://leetcode-cn.com/problems/partition-list/submis...

  • 86. 分隔链表

    https://leetcode-cn.com/problems/partition-list/solution/...

  • 86. 分隔链表

    给你一个链表的头节点 head 和一个特定值 x ,请你对链表进行分隔,使得所有 小于 x 的节点都出现在 大于或...

  • LeetCode 86. 分隔链表

    86. 分隔链表 给定一个链表和一个特定值 x,对链表进行分隔,使得所有小于 x 的节点都在大于或等于 x 的节点...

  • 每日一题2. 分隔链表

    86. 分隔链表 给定一个链表和一个特定值 x,对链表进行分隔,使得所有小于 x 的节点都在大于或等于 x 的节点...

网友评论

    本文标题:86. 分隔链表

    本文链接:https://www.haomeiwen.com/subject/esuvdqtx.html