This commit is contained in:
Omid Rajabi 2024-07-17 10:41:37 +09:00 committed by GitHub
commit 2b6540dd0c
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 106 additions and 0 deletions

View File

@ -269,4 +269,57 @@ export default class LinkedList {
return this; return this;
} }
/**
* @param {*} value
* @return {LinkedList}
*/
swap(data1, data2) {
let node1Prev = null;
let node2Prev = null;
let node1 = this.head;
let node2 = this.head;
// elements are same, no swap to be made
if (data1 === data2) {
return;
}
while (node1 !== null) {
if (node1.data === data1) {
break;
}
node1Prev = node1;
node1 = node1.next;
}
while (node2 !== null) {
if (node2.data === data2) {
break;
}
node2Prev = node2;
node2 = node2.next;
}
// swap not possible, one or more element not in list
if (node1 === null || node2 === null) {
return;
}
if (node1Prev === null) {
this.head = node2;
} else {
node1Prev.setNextNode(node2);
}
if (node2Prev === null) {
this.head = node1;
} else {
node2Prev.setNextNode(node1);
}
const temp = node1.next;
node1.setNextNode(node2.next);
node2.setNextNode(temp);
}
} }

View File

@ -7,4 +7,12 @@ export default class LinkedListNode {
toString(callback) { toString(callback) {
return callback ? callback(this.value) : `${this.value}`; return callback ? callback(this.value) : `${this.value}`;
} }
setNextNode(node) {
if (node instanceof LinkedListNode || node === null) {
this.next = node;
} else {
throw new Error('Next node must be a member of the Node class.');
}
}
} }

View File

@ -152,6 +152,51 @@ ReverseTraversal(head, tail)
end ReverseTraversal end ReverseTraversal
``` ```
### Swap
```text
Swap(head, data1, data2)
Pre: head is the head node in the list
data1 and data2 are valid values
Post: the 2 items in the list have been swapped
if data1 === data2
end Swap
node1Prev ← null
node2Prev ← null
node1 ← head
node2 ← head
while node1 != null
if node1.data === data1
break
node1Prev ← node1
node1 ← node1.next
end while
while node2 != null
if node2.data === data2
break
node2Prev ← node2
node2 ← node2.next
end while
if !node1 or !node2
end
endif
if !node1Prev
head ← node2
else
node1Prev.next ← node2
endif
if !node2Prev
head ← node1
else
node2Prev.next ← node1
endif
let temp ← node1.next
node1.next ← node2.next
node2.next ← temp
endSwap
```
## Complexities ## Complexities
### Time Complexity ### Time Complexity