I am implementing an Linked List and inside a function I am changing the head with some other element of Linked List, which appears proper inside that function when I console.log but outside that function when I console.log and iteratively print the data value, the head remains unchanged and the element with which I changed the head doesn't print
## My implementation of linked list
export class Node<T = number> {
public get data(): T {
return this._data;
}
public set data(v: T) {
this._data = v;
}
public next: Node<T> | null = null;
constructor(private _data: T) {}
}
export default class LinkedList<T = number> implements ILinkedList<T> {
static fromArray<T>(array: Array<T>): LinkedList<T> {
const ll = new LinkedList<T>();
for (let i = array.length - 1; i >= 0; i--) {
ll.insertInBegin(array[i]);
}
return ll;
}
print(): void {
let current = this.head;
while (current.next !== null) {
console.log(current.data);
current = current.next;
}
console.log(current.data);
}
public head: Node<T> | null = null;
#size: number = 0;
public get size(): number {
return this.#size;
}
insertInBegin(data: T): Node<T> {
const newNode = new Node(data);
newNode.next = this.head;
this.head = newNode;
this.#size++;
return newNode;
}
}
### This is what i want to do
function partition(head: Node | null, x: number): Node | null {
let current = head.next;
head.next = current.next;
current.next = head;
head = current;
console.log('Inside parititon:head', head);
// Inside parititon:head Node {
// _data: 4,
// next: Node { _data: 7, next: Node { _data: 3, next: [Node] } }
// }
return head;
}
const a = LinkedList.fromArray([7, 4, 3, 2, 5, 2]);
console.log('Before partition');
// Before partition
// 7
// 4
// 3
// 2
// 5
// 2
a.print();
partition(a.head, 3);
console.log('Outside head:', a.head);
// Outside head: Node {
// _data: 7,
// next: Node { _data: 3, next: Node { _data: 2, next: [Node] } }
// }
a.print();
// 7
// 3
// 2
// 5
// 2