Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 50 additions & 0 deletions Data-Structures/Linked-List/pairWiseSwap.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@

//problem link leetcode:https://leetcode.com/problems/swap-nodes-in-pairs/
class Node {
constructor(data) {
this.data = data;
this.next = null;
}
}

class LinkedList {
constructor(listOfValues) {
this.headNode = null;
this.tailNode = null;
this.length = 0;

if (listOfValues instanceof Array) {
for (const value of listOfValues) {
this.addLast(value);
}
}
}

pairwiseSwap() {
let current = this.headNode;
let prev = null;

while (current && current.next) {
const nextNode = current.next;
const nextNextNode = nextNode.next;

nextNode.next = current;
current.next = nextNextNode;

if (prev) {
prev.next = nextNode;
} else {
this.headNode = nextNode;
}

prev = current;
current = nextNextNode;
}

if (prev) {
this.tailNode = prev;
}
}
}

export { Node, LinkedList };