86. Partition List(js)

86. Partition List

Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.

You should preserve the original relative order of the nodes in each of the two partitions.

Example:

Input: head = 1->4->3->2->5->2, x = 3
Output: 1->2->2->4->3->5
题意:给定一个链表和一个数值x,要求将链表中小于x的移到链表前面,大于的节点不变
代码如下:
/**
 * 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 start=new ListNode(-1);
    start.next=head;
    let pre=start, cur=head;
    while(pre.next && pre.next.val<x) pre=pre.next;
    cur=pre;
    while(cur.next){
        if(cur.next.val<x){
            let node=cur.next;
            cur.next=node.next;
            node.next=pre.next;
            pre.next=node;
            pre=pre.next;
        }else{
            cur=cur.next;
        }
    }
    return start.next;
    
};

猜你喜欢

转载自www.cnblogs.com/xingguozhiming/p/10667067.html