LeetCode——86. 分隔链表

127 阅读1分钟

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

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

示例:

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

解题思路

  • 我们可以用两个指针before 和 after 来追踪上述的两个链表。两个指针可以用于分别创建两个链表,然后将这两个链表连接即可获得所需的链表。

代码实现

/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */
/**
 * @param {ListNode} head
 * @param {number} x
 * @return {ListNode}
 */
var partition = function(head, x) {
    let beforeHead = new ListNode(0) 
    let afterHead = new ListNode(0) 
    let before = beforeHead
    let after = afterHead
    let cur = head 
    while(cur){
        if(cur.val < x){
            before.next = cur
            before =  before.next
        }else{
            after.next = cur
            after =  after.next
        }
        cur = cur.next
    }
    after.next = null
    before.next = afterHead.next
    return beforeHead.next
};

性能

时间复杂度:O(n)

空间复杂度:O(1)