-
Notifications
You must be signed in to change notification settings - Fork 1
/
swapPairs.ts
70 lines (57 loc) · 1.59 KB
/
swapPairs.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
/*
Given a list, swap every two adjacent nodes.
Something to think about: How would your code change if this were a linked list, versus an array?
Example:
```js
> swapPairs([1,2,3,4])
> [2,1,4,3]
> swapPairs([])
> []
```
*/
export function swapPairsArray(pairs: number[]): number[] {
if (pairs.length % 2 !== 0) {
throw new Error('Uneven list');
}
const swapped: number[] = [];
for (let index = 0; index < pairs.length; index += 2) {
swapped.push(pairs[index + 1], pairs[index]);
}
return swapped;
}
export type Node = null | {
value: number;
next: Node;
};
export function swapPairsLinkedList(pairs: Node): Node {
// while structuredClone is not supported in TypeScript...
let currentNode: Node = JSON.parse(JSON.stringify(pairs));
if (currentNode == null) {
return null;
}
if (currentNode.next == null) {
throw new Error('Uneven list');
}
// swap the first two nodes
const secondNode = currentNode.next;
currentNode.next = secondNode.next;
secondNode.next = currentNode;
const swapped = secondNode; // to keep track of the head of the list
let previousNode = currentNode; // for the next swaps
currentNode = currentNode.next; // will start at the third node
while (currentNode != null) {
const nextNode: Node = currentNode.next;
if (nextNode == null) {
throw new Error('Uneven list');
}
// swap the current node with the next node
currentNode.next = nextNode.next;
nextNode.next = currentNode;
// and adjust the previous node
previousNode.next = nextNode;
previousNode = currentNode;
// move to the next node
currentNode = currentNode.next;
}
return swapped;
}