added linkedlist swap

This commit is contained in:
Omid Rajabi 2022-02-01 08:53:45 -05:00
parent 819f38f792
commit 21d54e4774
3 changed files with 110 additions and 0 deletions

View File

@ -2,6 +2,8 @@ import LinkedListNode from './LinkedListNode';
import Comparator from '../../utils/comparator/Comparator'; import Comparator from '../../utils/comparator/Comparator';
export default class LinkedList { export default class LinkedList {
head: any;
tail: any;
/** /**
* @param {Function} [comparatorFunction] * @param {Function} [comparatorFunction]
*/ */
@ -269,4 +271,59 @@ 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);
}
let 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

@ -149,6 +149,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