Categories
Uncategorized

143. Reorder List Leetcode Javascript Solution

The Problem:

You are given the head of a singly linked-list. The list can be represented as:

L0 → L1 → … → Ln - 1 → Ln

Reorder the list to be on the following form:

L0 → Ln → L1 → Ln - 1 → L2 → Ln - 2 → …

You may not modify the values in the list’s nodes. Only nodes themselves may be changed.

Example 1:

Input: head = [1,2,3,4]
Output: [1,4,2,3]

Example 2:

Input: head = [1,2,3,4,5]
Output: [1,5,2,4,3]

Constraints:

  • The number of nodes in the list is in the range [1, 5 * 104].
  • 1 <= Node.val <= 1000

The Solution:

var reorderList = function(head) {
    if(head == null) return head
let fast = head, slow = head
while(fast.next && fast.next.next){
    slow = slow.next
    fast = fast.next.next
}
    //console.log(fast.val)
    p2 = slow.next
    //console.log(p2)
    slow.next = null
    let prev = null
    while(p2){
        let next = p2.next
         p2.next = prev
        prev = p2
        p2 = next
    }
    console.log(prev)
    console.log(head)
    let part1 = head, part2 = prev
    while(part2){
        let p1 = part1.next
        let p2 = part2.next
        part1.next = part2
        part2.next = p1
        part1 = p1
        part2 = p2
    }
    return head
};
Categories
Uncategorized

1721. Swapping Nodes in a Linked List Leetcode Javascript Solution

The Problem:

You are given the head of a linked list, and an integer k.

Return the head of the linked list after swapping the values of the kth node from the beginning and the kth node from the end (the list is 1-indexed).

Example 1:

Input: head = [1,2,3,4,5], k = 2
Output: [1,4,3,2,5]

Example 2:

Input: head = [7,9,6,6,7,8,3,0,9,5], k = 5
Output: [7,9,6,6,8,7,3,0,9,5]

Example 3:

Input: head = [1], k = 1
Output: [1]

Example 4:

Input: head = [1,2], k = 1
Output: [2,1]

Example 5:

Input: head = [1,2,3], k = 2
Output: [1,2,3]

Constraints:

  • The number of nodes in the list is n.
  • 1 <= k <= n <= 105
  • 0 <= Node.val <= 100

The Solution:

I got stuck at trying a new element swapping method with ES6 and wasted a good amount of time. In the end, I printed out variables line by line and used the old swapping method.

var swapNodes = function(head, k) {
    let dummy = new ListNode(0)
    dummy.next = head
    let fast = dummy, slow = dummy
    for(let i = 1; i <= k; i++){
        fast = fast.next
    }
  //  console.log(fast.val)
    let first = fast
    while(fast.next != null){
        slow = slow.next
        fast = fast.next
    }
    let second = slow.next
    //console.log("first: " + first.val + " second: " + second.val)
   // first.val, second.val = second.val, first.val
    //let a = 2, b = 4
    let temp = first.val
    first.val = second.val
    second.val = temp
   // console.log( "a: " + a + " b: " + b)
   // console.log("first: " + first.val + " second: " + second.val)
    return dummy.next
};