Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

2022-10-12 #75

Open
github-actions bot opened this issue Oct 11, 2022 · 1 comment
Open

2022-10-12 #75

github-actions bot opened this issue Oct 11, 2022 · 1 comment

Comments

@github-actions
Copy link

No description provided.

@gongpeione
Copy link
Contributor

143 Reorder List

/*
 * @lc app=leetcode id=143 lang=typescript
 *
 * [143] Reorder List
 */

// @lc code=start
/**
 * Definition for singly-linked list.
 * class ListNode {
 *     val: number
 *     next: ListNode | null
 *     constructor(val?: number, next?: ListNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.next = (next===undefined ? null : next)
 *     }
 * }
 */

/**
 Do not return anything, modify head in-place instead.
 */
function reorderList(head: ListNode | null): void {
    // find the middle of this list
    let slowPointer = head;
    let fastPointer = head.next;
    while(fastPointer && fastPointer.next) {
        slowPointer = slowPointer.next;
        fastPointer = fastPointer.next.next;
    }

    // this is the start of the second list
    let secondHead = slowPointer.next;

    // break down the list
    slowPointer.next = null;

    // reverse the second list
    let prev = null;
    while(secondHead) {
        const tmp = secondHead.next;
        secondHead.next = prev;
        prev = secondHead;
        secondHead = tmp;
    }

    // reorder the list
    let firstList = head;
    let secondList = prev;
    while (secondList) {
        const tmp1 = firstList.next;
        const tmp2 = secondList.next;

        firstList.next = secondList;
        secondList.next = tmp1;
        firstList = tmp1;
        secondList = tmp2;
    }
};
// @lc code=end

Nickname: Geeku
From vscode-hzfe-algorithms

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant