47 lines
1.1 KiB
JavaScript
47 lines
1.1 KiB
JavaScript
/**
|
||
* Definition for singly-linked list.
|
||
* function ListNode(val, next) {
|
||
* this.val = (val===undefined ? 0 : val)
|
||
* this.next = (next===undefined ? null : next)
|
||
* }
|
||
*/
|
||
/**
|
||
* @param {ListNode} head
|
||
* @param {number} x
|
||
* @return {ListNode}
|
||
*/
|
||
import { ListNode } from './linked-list-tools';
|
||
|
||
const partition = function (head, x) {
|
||
|
||
};
|
||
|
||
/*
|
||
思路:遍历整个链表,把小于x的值连接到一个叫smallHead的哑节点上,把大于等于x的值连接到一个叫largeHead的哑节点上
|
||
之后把smallHead整个链表,和largeHead整个链表连接起来就行了
|
||
*/
|
||
function f1(head, x) {
|
||
let small = new ListNode(0);
|
||
let large = new ListNode(0);
|
||
const smallHead = small;
|
||
const largeHead = large;
|
||
|
||
// 遍历整个head表示的列表
|
||
while (head) {
|
||
if (head.val < x) {
|
||
small.next = head;
|
||
small = small.next;
|
||
} else {
|
||
large.next = head;
|
||
large = large.next;
|
||
}
|
||
head = head.next;
|
||
}
|
||
|
||
// 连接两个链表
|
||
small.next = largeHead.next;
|
||
large.next = null; // 思考1->2->3->1, x=2 这种情况 samllHead:1->1, largeHead:2->3->1,这个时候3->1是不应该存在的
|
||
|
||
return smallHead.next;
|
||
}
|