Skip to content

Commit

Permalink
Add 328 even odd linked list
Browse files Browse the repository at this point in the history
  • Loading branch information
escwxyz committed May 3, 2023
1 parent 9175f90 commit 8c5ee50
Showing 1 changed file with 65 additions and 0 deletions.
65 changes: 65 additions & 0 deletions typescript/src/328-odd-even-linked-list.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
// 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
}
}

/**
* @param head - linked list
* @returns sorted linked list
*
* Problem: https://leetcode.com/problems/odd-even-linked-list/description
*/
export function oddEvenList(head: ListNode | null): ListNode | null {
if (head == null || head.next == null) return head

const odd = new ListNode(-1)
const even = new ListNode(-1)

let p1 = odd
let p2 = even

let p: ListNode | null = head
let index = 1

while (p != null) {
if (index % 2 != 0) {
p1.next = p
p1 = p1.next
} else {
p2.next = p
p2 = p2.next
}
const tmp: ListNode | null = p.next
p.next = null
p = tmp
index++
}

p1.next = even.next

return odd.next
}

if (import.meta.vitest) {
const { test, expect } = import.meta.vitest
test('test one', () => {
expect(
oddEvenList(
new ListNode(
1,
new ListNode(2, new ListNode(3, new ListNode(4, new ListNode(5))))
)
)
).toStrictEqual(
new ListNode(
1,
new ListNode(3, new ListNode(5, new ListNode(2, new ListNode(4))))
)
)
})
}

0 comments on commit 8c5ee50

Please sign in to comment.